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

MobX 中装饰器无法正常生效的原因是什么?

MobX 装饰器不生效问题说明

如果未调用makeAutoObservable(this)函数,MobX 的相关装饰器将无法正常生效。

以下是问题复现的完整代码示例:

组件代码

import { observer } from 'mobx-react-lite'
import useStore from 'hooks/useStore'

const Counter = props => {
  const { counterStore } = useStore()
  const { countValue } = counterStore
  console.log(counterStore)
  return (
    <div>
      <button>-</button>
      <p>{countValue} значение</p>
      <button onClick={counterStore.incrementCountValue}>+</button>
    </div>
  )
}

export default observer(Counter)

异常Store代码(未调用makeAutoObservable)

import { action, observable } from 'mobx'

export default class CounterStore {
  @observable countValue = 0

  @action incrementCountValue = () => {
    this.countValue = this.countValue + 1
  }
}

修复方案

只需要在Store类的构造函数中调用makeAutoObservable(this),所有功能即可正常运行,修复后的Store示例如下:

import { makeAutoObservable, action, observable } from 'mobx'

export default class CounterStore {
  @observable countValue = 0

  constructor() {
    makeAutoObservable(this)
  }

  @action incrementCountValue = () => {
    this.countValue = this.countValue + 1
  }
}

内容的提问来源于stack exchange,提问作者bazmexes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:27:04