MobX异步反应导致Promise警告

时间:2018-03-05 00:08:37

标签: javascript mobx

我商店的简化版......

export class DataStore {
    api;

    @observable prop1;
    @observable prop2;

    @observable data1;
    @observable data2;

    constructor(api) {
        this.api = api

        reaction(
            () => this.prop1,
            (id, reaction) => {
                this.loadData1();
            }
        );

        reaction(
            () => this.prop2,
            (id, reaction) => {
                this.loadData2();
            }
        );
    }

    @action
    async loadData1() {
        let results = await this.api.getData1(
            this.prop1
        );
        runInAction(() => { 
            this.data1 = results.data;
        });
    }

    async loadData2() {
        let results = await this.api.getData2(
            this.prop2
        );
        runInAction(() => { 
            this.data2 = results.data;
        });
    }
}

prop1反应首先触发而没有问题。一旦prop2反应触发,我在控制台中收到以下消息。

  

警告:承诺是在处理程序中创建的,但未从中返回

我已经在圈子中调试自己,似乎无法追查警告的原因。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

reaction中的回调函数也可以是async。 我建议在调用prop函数之前验证loadData

export class DataStore {
    @observable prop1;
    @observable prop2;

    @observable data1;
    @observable data2;

    constructor(api) {
        this.api = api;

        reaction(() => this.prop1,
            async (prop1) => { prop1 && (await this.loadData1()); }
        );

        reaction(() => this.prop1,
            async (prop2) => { prop2 && (await this.loadData2()); }
        );
    }

    @action
    asnyc loadData1() {
        const results = await this.api.getData1(this.prop1);
        this.data1 = results.data;
    }

    @action
    asnyc loadData2() {
        const results = await this.api.getData2(this.prop2);
        this.data2 = results.data;
    }
}