reactjs - Mobx 状态树引用类型和 Typescript

标签 reactjs typescript mobx mobx-react mobx-state-tree

我在 React 应用程序中使用带有 Typescript 的 mobx-state-tree。而且,我在使用 Typescript 时遇到了问题,它提示 mobx 类型的类型 types.safeReference .看起来像safeReference的类型当您使用 .create() 时,模型定义与其类型不同实际创建模型的实例。在我的代码中,selectedProduct的类型转换为 string | number | undefined | nullproductStore ,但在模型定义中是 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
});
而且,这是我的根存储:
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.
});
更新:
重现此问题的另一种方法是尝试创建自定义引用。 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
      }
  })
)

最佳答案

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

export const rootStore = RootStore.create({
    productStore: castToSnapshot(productStore)
});

关于reactjs - Mobx 状态树引用类型和 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65958595/

相关文章:

typescript - Sublime Text 3 Typescript 不允许缩进和单引号

javascript - 对复杂数据元素的引用

javascript - 如何有条件地将名称附加到字符串?

javascript - 无法在没有装饰器支持的情况下使类成为 mobx 观察者 - "TypeError Cannot read property ' 未定义的观察者”

redux - Aurelia 状态管理

javascript - 在 react-select 中的 input 元素前添加一个图标

javascript - 智能组件和dumb组件的不同 Prop 状态

javascript - 在 React 中,如何在 HTML 表格中显示来自 API 的数据?

reactjs - 错误 : [mobx] Computed values are not allowed to cause side effects by changing observables that are already being observed. 试图修改:

reactjs - React Redux - 如何从静态函数访问结构化选择器?