TypeError: Cannot 读取属性的 空 (读取 'setState')
错误信息
Cannot 读取属性的 空 (读取 'setState')
快速摘要
你 called `这个.setState()` 但 `这个` 是空 or undefined, 通常因为方法 wasn't properly 边界.
为什么发生
类方法通过 as 回调不使用 binding
Used
这个.方法不使用 arrow 函数 or .bind()Called setState in detached 回调
最小示例
✗ 错误代码
class Component extends React.Component {
handleClick() {
this.setState({ count: 1 }); // this is undefined!
}
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}✓ 修复代码
class Component extends React.Component {
handleClick = () => {
this.setState({ count: 1 }); // this is bound
}
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}Arrow 函数类 属性 automatically bind 这个 到实例, fixing undefined 这个错误.
如何诊断
检查如何方法是 通过到 事件处理函数 or 回调
验证
这个是边界正确地 (arrow 函数 or constructor bind)Log
这个内部方法
如何修复
Use arrow 函数类 属性:
handleClick = () => { ... }Bind in constructor:
这个.handleClick = 这个.handleClick.bind(这个)Use arrow 函数 inline:
onClick={() => 这个.handleClick()}
如何预防
Use arrow 函数类 属性 for 事件处理函数
Or convert 到函数组件使用 Hook
相关资源
相关课程
- 事件 Handling
学习事件处理函数 binding.