MobX React Native 抛出无法读取 undefined 的属性



我正在尝试将一个mobX商店传递给另一个商店,以下是我的商店代码:

商店类别 1:

export default class APIKeyStore
{
@persist @observable apiKey = '****';
}

商店类别 2:

export default class ServiceCalls
{
@persist @observable apiKeysStore;
constructor(apiStore)
{
this.apiKeysStore = apiStore; 
console.log('constructor', this.apiKeysStore.apiKey);
}
@action async initializeApp()
{
console.log('initializeApp', this.apiKeyStore.apiKey);
}
}

索引.js:

import APIKeyStore from './models/APIKeyStore';
import ServiceCalls from './models/ServiceCalls';
const serviceCalls = new ServiceCalls(new APIKeyStore())
const stores = {
serviceCalls: serviceCalls
}
export default
{
...stores
};

我调用商店 2 的初始化App(( 方法的组件文件:

@inject('serviceCalls')
@observer
class ZeroStepScreen extends Component
{
async componentWillMount()
{
try
{
console.log('componentWillMount', this.props.serviceCalls.apiKeysStore.apiKey);
await this.props.serviceCalls.initializeApp();
}
catch(e)
{
console.log(e);
}
}
}

在上面的类中,我有三个console.log(..)声明 - 它报告来自第二个存储constructor的正确结果,以及组件的componentWillMount()方法。

当调用同一个第二个存储类的initializeApp()方法时,this.apiKeysStore.apiKey总是抛出我无法读取未定义的属性。

二等构造函数 -console.log(this.apiKeysStore.apiKey)- 确定

零步屏 -console.log(this.props.serviceCalls.apiKeysStore.apiKey)- 确定

第 2 类' 初始化应用程序(( -console.log(this.apiKeysStore.apiKey)- 错误

我无法理解我做错了什么,即第二个存储类在访问时未定义this.apiKeysStore.apiKey当其构造函数报告正确时,组件类报告正确。

我不太确定基础知识(以这些方式做事(,但最终遵循的方式对我有用:

@action async initializeApp()
{
console.log(this.getAPIKeyStore()).apiKey);
}
getAPIKeyStore()
{
return this.apiKeysStore;
}

可能使用async我无法直接访问类级别的观察者。

最新更新