Mobx State Tree子模型调用父模型action报错:fetchDataset不是函数
排查Mobx State Tree子模型调用根模型方法报错:
self.root.fetchDataset is not a function 可能的原因及解决方法
1. 错误直接访问self.root,未使用MST的getRoot工具函数
MST中子模型无法直接通过self.root获取根节点,必须借助官方提供的getRoot(self)工具函数来获取根实例。
错误示例:
// TranslationsDataModel 中的错误写法 actions(self => ({ async someAction() { await self.root.fetchDataset(); } }))
修正后:
import { getRoot } from "mobx-state-tree"; // TranslationsDataModel 中的正确写法 actions(self => ({ async someAction() { const root = getRoot(self); await root.fetchDataset(); } }))
2. fetchDataset未定义在根模型的actions中
要确保fetchDataset是根模型DataModel的action方法——MST中只有定义在actions块里的方法才能被其他模型调用,放在views里的只读方法无法满足需求。
错误示例:
// DataModel 中的错误定义 const DataModel = types.model({ translations: types.optional(TranslationsDataModel, {}) }).views(self => ({ fetchDataset() { // ...请求逻辑 } }))
修正后:
const DataModel = types.model({ translations: types.optional(TranslationsDataModel, {}) }).actions(self => ({ async fetchDataset() { // ...异步请求逻辑 } }))
3. 子模型未正确挂载到根模型实例
如果TranslationsDataModel是单独实例化的,没有作为DataModel的属性被创建,子模型实例就没有关联到根节点,此时调用根方法必然失败。
错误示例:
// 错误:单独实例化子模型 const translations = TranslationsDataModel.create({}); translations.someAction();
正确做法:
// 先实例化根模型,子模型作为根的属性自动创建 const rootStore = DataModel.create({}); rootStore.translations.someAction();
4. 方法名拼写或大小写不一致
检查fetchDataset的方法名是否和调用时完全一致,比如是否误写为fetchData、FetchDataset等。
内容的提问来源于stack exchange,提问作者marielle
相关产品推荐
相关产品推荐

