未绑定的事件处理程序接收器¶
ID: js/unbound-event-handler-receiver
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- correctness
Query suites:
- javascript-security-and-quality.qls
事件处理程序回调通常作为函数调用,而不是作为方法调用。这意味着此类回调的 `this` 表达式将评估为 `undefined` 或全局对象。因此,使用 ES6 类方法作为回调意味着该方法的 `this` 表达式不会引用类实例。
建议¶
确保使用 `this` 表达式的事件处理程序方法的接收器对象不是 `undefined`。例如,你可以使用 `bind` 或显式地将该方法作为方法调用来调用。
示例¶
以下示例(适用于 React 框架)将 `handleClick` 方法注册为 `click` 事件的事件处理程序
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}> // BAD `this` is now undefined in `handleClick`
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
这存在问题,因为这会将 `handleClick` 作为函数调用而不是方法调用,这意味着 `handleClick` 内部的 `this` 为 `undefined`。
相反,在构造函数中绑定 `handleClick` 的接收器
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}> // GOOD, the constructor binds `handleClick`
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
参考¶
React 快速入门:处理事件。