MobX点击触发store方法时报TypeError: Cannot read properties of undefined求助
问题根源
报错是类方法的this指向丢失导致的。当你直接把store.increaseNumber作为onClick回调传递时,方法脱离了store实例的运行上下文,触发时this不再指向CounterStore的实例,因此无法读取this上的属性抛出TypeError。
解决方案
可任选以下任意一种方案修复:
方案1:将store方法改写为箭头函数(推荐)
修改store.tsx的increaseNumber定义,箭头函数会永久绑定this到当前实例:
import { observable, computed, action, makeObservable, override, makeAutoObservable } from "mobx" class CounterStore { initValue = 0 powValue = Math.pow(this.initValue, 2) constructor() { makeAutoObservable(this) } // 改为箭头函数 increaseNumber = () => { this.initValue = this.initValue + 1 } } const Store = new CounterStore() export default Store
方案2:调用时用箭头函数包裹回调
修改increasement.tsx的按钮点击绑定:
<button onClick={() => store.increaseNumber()}>Increase</button>
方案3:调用时用bind手动绑定this指向
同样修改increasement.tsx的按钮点击绑定:
<button onClick={store.increaseNumber.bind(store)}>Increase</button>
内容的提问来源于stack exchange,提问作者Lê Quốc Khánh
相关产品推荐
相关产品推荐

