You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:48:00