mobx-utils 的 createTransformer 生成的函数结果未被记忆

Result of function made by createTransformer from mobx-utils is not memoized

我正在尝试使用 MobX 6 和相应版本的 mobx-utils.

实现带有参数 shown in this answer 的计算 getter 函数
export class CodificatorStore {
  @observable.ref items: Array<Codificator> | null = null;

  @action setItems(items: Array<Codificator>): void {
    this.items = items;
  }

  @computed get item(): ITransformer<number, Codificator | null> {
    return createTransformer((index: number): Codificator | null => {
      console.log(`get item by index: ${index}`);
      return this.items ? this.items[index] : null;
    });
  }
}

我希望创建的函数能够在每次使用相同的参数和相同的(未更改的)可观察对象调用它时记住其执行结果 items 但是我在 render 中每次调用时都会收到一条新的记录消息我的 React 组件的方法:

codificatorStore.item(0);

根据 docs and source code,我希望在所有连续调用中从 reactiveView 返回记忆值,而不是调用我的转换函数。我误解了什么吗?我怎样才能达到预期的效果?

首先,这么简单的操作真的需要记忆吗?或者它只是一个例子?

其次,如果您只需要记忆,则根本不需要 createTransformer,它的用途有点不同。但是你可以使用 computedFn,像这样:

import { computedFn } from 'mobx-utils';

// ...

  item = computedFn((index) => {
    console.log(`get item by index: ${index}`);
    return this.items ? this.items[index] : null;
  });

Example on Codesandbox