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
相关产品推荐
相关产品推荐

