如何使用 mobx 让自动运行与 runInAction 一起工作?

How can I get autorun to work with runInAction, using mobx?

正在尝试学习 mobx 和 runInAction,但很难理解为什么 autorun 在以下示例中没有调用我的回调:

class FooClass {

    // constructor() {
    //     this.fooMethod();
    // }

    @observable myBool = false;

    async fooMethod() {

        await new Promise(r => setTimeout(r, 1000));
        runInAction(() => this.myBool = true); // <--- myBool: true is never logged to the console. why?
        await new Promise(r => setTimeout(r, 3000));
        runInAction(() => this.myBool = false); // <--- also not logged
    }
}

let foo = new FooClass();

foo.fooMethod();
autorun(() => console.log("myBool:", foo.myBool));

使用带有装饰器的 TypeScript 和 babel。

据我了解,如果您想在不在标记为操作的方法内时更改某些可观察值,可以使用 runInAction(...) 吗?

为什么我的脚本不起作用?

您可能正在使用 MobX v6,它的 api 稍微改变了一点,您现在需要在构造函数中添加 makeAutoObservablemakeObservable 调用,例如:

import { autorun, makeAutoObservable, observable, runInAction } from 'mobx';

class FooClass {
  constructor() {
    makeAutoObservable(this);

    autorun(() => console.log('myBool:', this.myBool));
    this.fooMethod();
  }

  // You can actually remove decorator here if you use `makeAutoObservable`
  @observable myBool = false;

  async fooMethod() {
    await new Promise((r) => setTimeout(r, 1000));
    runInAction(() => (this.myBool = true)); // it will be logged now
    await new Promise((r) => setTimeout(r, 3000));
    runInAction(() => (this.myBool = false)); // it will be logged now too
  }
}

new FooClass();

Codesandbox

More info in the docs