typescript/unbound-method 正确性
它的作用
此规则强制要求未绑定的方法必须在预期的作用域中调用。
为什么这是个问题?
当你从对象中提取一个方法并单独调用它时,this 上下文会丢失。这可能导致运行时错误或意外行为,特别是当方法依赖于 this 来访问实例属性或其他方法时。
示例
以下为 不正确 的代码示例:
ts
class MyClass {
private value = 42;
getValue() {
return this.value;
}
processValue() {
return this.value * 2;
}
}
const instance = new MyClass();
// 未绑定的方法 - 失去了 'this' 上下文
const getValue = instance.getValue;
getValue(); // 运行时错误:无法读取 undefined 的 property 'value'
// 将未绑定的方法作为回调传递
[1, 2, 3].map(instance.processValue); // 'this' 将为 undefined
// 解构方法
const { getValue: unboundGetValue } = instance;
unboundGetValue(); // 运行时错误以下为 正确 的代码示例:
ts
class MyClass {
private value = 42;
getValue() {
return this.value;
}
processValue() {
return this.value * 2;
}
}
const instance = new MyClass();
// 在实例上调用方法
const value = instance.getValue(); // 正确
// 绑定方法以保持上下文
const boundGetValue = instance.getValue.bind(instance);
boundGetValue(); // 正确
// 使用箭头函数保持上下文
[1, 2, 3].map(() => instance.processValue()); // 正确
// 在类中使用箭头函数实现自动绑定
class MyClassWithArrow {
private value = 42;
getValue = () => {
return this.value;
};
}
const instance2 = new MyClassWithArrow();
const getValue = instance2.getValue; // 安全 - 箭头函数保持了 'this'
getValue(); // 正确配置
此规则接受一个配置对象,包含以下属性:
ignoreStatic
type: boolean
默认值: false
是否忽略静态的未绑定方法。 当设置为 true 时,静态方法可以被引用而无需绑定。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/unbound-method": "error"
}
}bash
oxlint --type-aware --deny typescript/unbound-method