MobX异步反应导致Promise警告

问题描述 投票:0回答:1

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

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反应触发,我在控制台中收到以下消息。

警告:在处理程序中创建了一个promise,但未从中返回

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

javascript mobx
1个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.