Mobx 状态树引用类型和 Typescript

ata*_*ati 6 typescript reactjs mobx mobx-react mobx-state-tree

我在 React 应用程序中使用带有 Typescript 的 mobx-state-tree。而且,我在使用 Typescript 时遇到了问题,它抱怨 mobx type 的类型types.safeReference。看起来safeReference模型定义中的类型与您.create()实际创建模型实例时使用的类型不同。在我的代码中,selectedProduct的类型被转换为string | number | undefined | nullin productStore,但在模型定义中是IStateTreeNode<...> | undefined | null,这就是我在我的根存储中收到错误的原因。我该如何解决?

这是我的产品商店:

import { types } from "mobx-state-tree";

const Product = types.model("Product", {
   id: types.identifier,
   name: types.string
})

const ProductStore = types
  .model("ProductStore", {
    products: types.array(Product),
    selectedProduct: types.safeReference(Product),
  })
  .actions((self) => ({
      // actions here
  }));

export const productStore = ProductStore.create({
  products: [],
  selectedProduct: undefined // the type here is different from the type in the actual model
});
Run Code Online (Sandbox Code Playgroud)

而且,这是我的根存储:

import { types } from "mobx-state-tree";
import ProductStore, { productStore } from "./product-store";

const RootStore = types.model('RootStore', {    
  productStore: ProductStore 
})

export const rootStore = RootStore.create({
    productStore: productStore // Here is where I get the typescript error.
});
Run Code Online (Sandbox Code Playgroud)

更新:

重现此问题的另一种方法是尝试创建自定义引用。getter 会抱怨undefined不能分配到类型 {...}。

const ProductByIdReference = types.maybeNull(
  types.reference(Product, {
      get(id: number, parent: Instance<typeof ProductStore>) {
          return parent.products.find(p => p.id === id) || undefined
      },
      set(value: Instance<typeof Product>) {
          return value.id
      }
  })
)
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 5

一般来说,当您尝试使用通常使用实例的快照时,您可以使用cast. 当您尝试使用通常使用快照的实例时,您可以使用castToSnapshot.

export const rootStore = RootStore.create({
    productStore: castToSnapshot(productStore)
});
Run Code Online (Sandbox Code Playgroud)