MobX React Native throws无法读取undefined的属性

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

我正试图将一个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) - 好的

ZeroStepScreen - console.log(this.props.serviceCalls.apiKeysStore.apiKey) - 好的

第二类'initializeApp() - console.log(this.apiKeysStore.apiKey) - 错误

当构造函数报告正确,组件类报告正确时,我无法理解第二个商店类在访问this.apiKeysStore.apiKey时未定义的错误。

react-native mobx mobx-react mobx-persist
1个回答
0
投票

我不完全确定基本面(做这些事情的方式),但最后的方式对我有用:

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

getAPIKeyStore()
{
  return this.apiKeysStore;
}

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

© www.soinside.com 2019 - 2024. All rights reserved.