MobX 异步反应

MobX async reaction

嗨,我在商店中使用 MobX,当计算值发生变化时,我需要有一个异步反应:

class Store {
    @observable user;
    @observable something;

    @computed get firstParam () {
         return this.user && this.user.params[0];
    }

    async loadSomething () {
        reaction(
                () => this.firstParam,
                async (param) => {
                    const { data: something } = await axios.get(`url/${param}`);

                    runInAction('update state after fetching something', () => {
                        this.something = something;
                    });
                }
            );
     }

}

我想知道除了 运行 条件之外,使用 when 而不是 reaction 会有什么区别?

when(
    () => !!this.firstParam,
    async () => {
         // fetch using this.firstParam
    }
)
        reaction(
            () => this.firstParam,
            async (param) => {
                const { data: something } = await axios.get(`url/${param}`);

                runInAction('update state after fetching something', () => {
                    this.something = something;
                });
            }
        );

这将仅跟踪 this.firstParam,当 return 一个新数据时,它将调用

            async (param) => {
            const { data: something } = await axios.get(`url/${param}`);

            runInAction('update state after fetching something', () => {
                this.something = something;
            });

现在,如果你选择 when 我相信它最终会做同样的事情, 摘自 mobx 文档:

You can use observable data structures as a promise... After completing the asynchronous action, just update your data

所以我看不出有什么理由不在你的情况下使用 when

请注意,when 只执行它的效果 一次,然后停止。所以在你的情况下,数据只会被获取一次。