react-native - MobX React Native 抛出无法读取未定义的属性
问题描述
我正在尝试将一个 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);
}
}
index.js:
import APIKeyStore from './models/APIKeyStore';
import ServiceCalls from './models/ServiceCalls';
const serviceCalls = new ServiceCalls(new APIKeyStore())
const stores = {
serviceCalls: serviceCalls
}
export default
{
...stores
};
我在其中调用 store 2 的 initializeApp() 方法的组件文件:
@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)
- OK
ZeroStepScreen - console.log(this.props.serviceCalls.apiKeysStore.apiKey)
- 好的
第二类'initializeApp() - console.log(this.apiKeysStore.apiKey)
- 错误
我无法理解我做错了什么,当第二个商店类this.apiKeysStore.apiKey
在其构造函数报告正确时访问时未定义,组件类报告正确。
解决方案
我不太确定基本原理(做这些事情的方式),但最终的方式对我有用:
@action async initializeApp()
{
console.log(this.getAPIKeyStore()).apiKey);
}
getAPIKeyStore()
{
return this.apiKeysStore;
}
可能使用async
我无法直接访问类级别的观察者。
推荐阅读
- flutter - Dart Completer.complete() 结果永远不会解决
- javascript - AWS Cognito - 创建用户而不向他们发送验证电子邮件
- php - 为什么方法不返回值?
- php - 如何在 Laravel 的 Amazon S3 中获取对象的存储类
- go - 在频道中使用引用是错误/坏事吗?
- r - 分组、汇总和转置
- data-science - 主题连贯性(gensim CoherenceModel)是否也仅根据我的语料库或外部数据计算?
- relation - 这个关系证明有问题吗?
- php - 我的网站上的 PHP 联系表单错误。PHP 新手,但我发誓这之前有效并且停止了,我无法弄清楚如何修复它
- firebase - Firestore 限制每小时或每天的读写次数,以防止用户在检查器中设置计时器