`console.log` 一个 mobx `@observable` 每当它的值改变时

`console.log` a mobx `@observable` whenever its value changes

有什么方法可以让 console.log 在 mobx @observable 更改值时自动触发?

我会用 mobx 开发工具来做,但它会触发大量控制台日志,因此很难确定我正在跟踪的 属性 值。

你可以这样做:

//store.js
import { autorun } from 'mobx';
autorun(() => {
  console.log(store.value); //value is an observable.
});

你也可以使用Reaction, 对于日志记录,您可能希望使用 auto运行,但您应该知道还有另一种选择,即 可以让您更好地控制何时 运行 您的回调。

我也喜欢它,因为语法更有意义:

import { reaction } from 'mobx'

class SomeStore {
    @observable item;
    @observable otherObservable;

    constructor() {
        reaction(
            // The callback will run only on change 
            // of observables described in this function
            () => this.item,
            // You can use whatever observables/computed values in this function
            // without making the function run on an unwanted observables change
            () => {
                if (this.otherObservable) {
                    doSometing();
                }
            }
        )
    }
}

此功能还有更多选项,您可以在提供的link中阅读。