为什么 MobX 允许我在没有 @action 的情况下更改这个 属性?

Why does MobX allow me to change this property without @action?

为什么 MobX 在严格模式下允许我从构造函数调用的切换方法中更改标志?它不应该告诉我"mobx is in strict mode, you should use an action"吗?

代码如下

import { useStrict, configure, autorun } from 'mobx';
import { observable, action, computed } from 'mobx';


configure({ enforceActions: true });


class Test {
    @observable flag = false;

    constructor() {
        this.toggle();
    }

    toggle() {
        this.flag = !this.flag;
    }
}

var t = new Test();

autorun(function test () {
    console.log("fired: " + t.flag);  //prints fired: true
});

感谢@ChrisEdgegington,只有在构造函数被调用后,属性才会变成可观察的,这也是合乎逻辑的,因为对象在构造函数被调用之前不存在。

您基本上只是将 flag 字段初始化两次,我希望 dis-advice 您不要这样做。

class Test {
    @observable flag = true;
}
// is the same as:
class Test {
    @observable flag;
    constructor() {
        this.flag = true;
    }
}

所以只使用一种方式,而不是两种方式。