MobX - 在另一个商店中访问时,使用 fromPromise 在商店构造函数中承诺的可观察值保持为空?

MobX - Observable value promised in a store constructor using fromPromise stays null when accessed in another store?

所以我有 2 家商店,一家 AuthorStore:

class AuthorStore {
  constructor() {
      // has author.name and is always present in storage
      AsyncStorage.getItem('author').then(action((data) => {
        this.author = JSON.parse(data);
      }));
  }

  @observable author = null;
}

和一个BookStore:

import AuthorStore from 'authorStore';
class BookStore {
  @observable book = {
    authorName: AuthorStore.author.name,
    bookTitle: null
  }
}

我一直在 BookStore 中收到错误,它无法获取 null 的 属性,就好像 AuthorStore.author.name 为空一样。所以它从 AuthorStore 中读取默认的 author 值,而无需构造函数 运行 首先为其赋值。

我遇到了新的 mobx-utils fromPromise,如果它存在于本地存储中,我认为它会得到 author 值,并等待 AsyncStorage 分配它到 author observable,所以它可以从另一个商店调用而不是 null.

我尝试在 AuthorStore 中首先使用 fromPromise 来记录 author 值,但它在控制台中显示为 Got undefined,而通常的 nullAuthorStore.author 部分出现 BookStore 错误。

更新:

class AuthorStore {
  @observable author = null;

  @computed get theAuthor() {
    authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)));

    // combine with when..
    when(
      () => authorPromise.state !== "pending",
      () => {
        console.log("Got Author", authorPromise.reason || authorPromise.value) // This runs, and returns author
        console.log("Got Name", authorPromise.reason || authorPromise.value.name) // This runs, and returns name
        return authorPromise.value; // This doesn't get returned in BookStore when calling this computed
      }
    );
  }
}

class BookStore {
  @observable book = {
    authorName: AuthorStore.theAuthor.name, // doesn't get computed returned value from promise
    bookTitle: null
  }
}

如何将 AuthorStore 计算函数 theAuthor 分配的 fromPromise 值变为 return 承诺的 authorPromise 值到 BookStoreauthorName?

FromPromise 创建一个新对象来包装原来的承诺。所以你的 authorFromStorage 在你的例子中只是一个正常的承诺,根本没有 state 属性 。因此,您应该将代码更改为:

authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)))

然后 when(() => authorPromise.state !== "pending") 等..

** 更新**

class AuthorStore {
  @observable author = null;

  constructor() {
    AsyncStorage.getItem('author').then(data => { this.author = JSON.parse(data) });
  }
}

class BookStore {
  @observable book = {
    authorName: function() {  // a function in an observable creates a computed prop
      return AuthorStore.author && AuthorStore.author.name
    },
    bookTitle: null
  }
}