You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用MobX-State-Tree定义含未知属性的递归Tree模型

用MobX-State-Tree实现递归Tree模型

对应你给出的TypeScript递归类型:

type Tree = {
  question: string,
  field: string,
  options: Record<string, Tree>
};

在MobX-State-Tree中可以通过types.map和types.late组合来实现这个递归结构,解决options的类型定义问题,完整代码如下:

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

export const Tree = types
  .model("Tree")
  .props({
    question: types.string,
    field: types.string,
    // types.map 对应TS的Record<string, Tree>,types.late处理递归引用
    options: types.map(types.late(() => Tree))
  })

关键说明:

  • types.map:用来实现类似TS中Record<string, T>的键值对结构,键为字符串类型,值为指定的MST模型实例
  • types.late(() => Tree):由于Tree模型是递归引用自身,需要用late延迟类型解析,避免在模型定义阶段出现未定义的引用错误

示例初始化

你可以这样创建一个符合结构的实例:

const demoTree = Tree.create({
  question: "是否需要进一步筛选?",
  field: "needFilter",
  options: {
    yes: {
      question: "按时间还是按类别筛选?",
      field: "filterType",
      options: {}
    },
    no: {
      question: "确认结束筛选?",
      field: "confirmEnd",
      options: {}
    }
  }
})

内容的提问来源于stack exchange,提问作者DaniloMourelle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:37