Mobx:观察对象的反应不起作用

Mobx: reaction for observing object doesn't work

这是我的商店:

import { observable, action, flow, reaction } from "mobx";

export default class Demo {
  @observable obj = {
    flag: false,
    name: "",
    age: 20
  };

  @action
  turnFlag = () => {
    this.obj.flag = true;
  };

  constructor() {
    reaction(
      () => this.obj,
      obj => {
        console.log(obj.flag);
      }
    );
  }
}

我想做的是,如果 obj 中的任何 属性 发生变化,将调用反应回调。

但是当动作turnFlag执行时,什么也没有发生。

那么我的代码有什么问题?如果我希望主管在 obj 有任何改变,我应该怎么做?

让我们试试

`import { observable, action, flow, reaction } from "mobx";

class Demo {
  @observable obj = {
    flag: false,
    name: "",
    age: 20
  };

  @action
  turnFlag = () => {
    this.obj.flag = true;
  };

  constructor() {
    reaction(
      () => this.obj,
      obj => {
        console.log(obj.flag);
      }
    );
  }
}
export default Demo;

`

为了使反应起作用,您需要让它在可观察对象上观察 属性,而不是根 obj

reaction(
  () => this.obj.flag,
  flag => { console.log(`FOO: ${flag}`); }
);

这里有一个工作示例:https://codesandbox.io/s/km3n38yrj7

(打开浏览器控制台查看输出。)

documentation 在这里介绍:

It is important to notice that the side effect will only react to data that was accessed in the data expression, which might be less then the data that is actually used in the effect.

在您的原始代码中,您没有访问 'obj' 上的任何内容。

由于您想在 'obj' 上的任何内容发生更改时执行某些操作:

What I want do is, if any property in obj changed, the reaction callback will be invoked.

听起来你想要 'observe'

observe(this.obj, change => {
  console.log(
    `${change.type} ${change.name} from ${change.oldValue}` +
      ` to ${change.object[change.name]}`
  );
});

我已经更新了 codesandbox link 以证明这一点。