为什么 Mobx 声称我正在尝试更改可观察值?

Why does Mobx claim I am trying to change an observable value?

每次我尝试访问 mobx class 实例的计算值时,我得到

[MobX] Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: VoiceSettings@3.voices

我创建了一个 class 像这样:

import {action, computed, makeObservable, observable} from "mobx"

export default class VoiceSettings {
    @observable language: Language = 'en';
    @observable speaker?: Voice;
    @observable voices: Voice[] = [];

    constructor() {
        makeObservable(this);
        this.getAvailableVoices();
    }

    async getAvailableVoices() {
        this.voices = await Speech.getAvailableVoicesAsync();
        return this.voices;
    }

    @computed
    get speakers(): string[] {
        return this.voices
            .filter(voice => voice.language.startsWith(this.language))
            .map(voice => voice.name)
    }

    @action
    setLanguage(language: Language) {
        this.language = language;
    }
}

export const voiceSettings = new VoiceSettings();

这似乎只有在我调用 voiceSettings.speakers 时才会发生。

更新 我的错。被错误信息绊倒了。我在代码

的其他地方调用方法 voice. getAvailableVoices()

问题是只有对可观察数据的同步更改才能在操作中起作用,因此当 Speech.getAvailableVoicesAsync() 已解决并分配给 this.voices 时,从技术上讲它不再在操作中。

如何创建异步操作是 discussed in the documentation。一种解决方法是使用 runInAction:

async getAvailableVoices() {
    const voices = await Speech.getAvailableVoicesAsync();

    runInAction(() => {
        this.voices = voices;
    });

    return this.voices;
}