如果对象已经是同一或另一个状态树的一部分,则无法将对象添加到状态树

发布于 2025-01-20 12:14:32 字数 318 浏览 2 评论 0原文

mobx-state-tree.module.js?f7d3:2154未接收错误:[mobx-state-tree]如果已经是同一或另一个状态树的一部分,则不能将对象添加到状态树中。

I get this error just by filtering through another state:

const data = self.allData.slice(0, 20);
self.sliced = data

Anyone has any idea what's wrong?

mobx-state-tree.module.js?f7d3:2154 Uncaught Error: [mobx-state-tree] Cannot add an object to a state tree if it is already part of the same or another state tree.

I get this error just by filtering through another state:

const data = self.allData.slice(0, 20);
self.sliced = data

Anyone has any idea what's wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我做我的改变 2025-01-27 12:14:32

在状态树中不能两次存在节点。取而代之的是,您可以将切成薄片数据建模为参考文献 它应该按预期工作。

示例

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

const Thing = types.model({
  id: types.identifier
});

const RootStore = types
  .model({
    allData: types.array(Thing),
    sliced: types.maybe(types.array(types.reference(Thing)))
  })
  .actions((self) => ({
    setSliced() {
      const data = self.allData.slice(0, 20);
      self.sliced = data;
    }
  }));

const rootStore = RootStore.create({
  allData: Array.from({ length: 40 }, (_, index) => ({ id: index.toString() }))
});

console.log(rootStore.sliced); // undefined
rootStore.setSliced();
console.log(rootStore.sliced); // (20) [Object, Object, ...]

A node cannot exist twice in the state tree. You could instead model your sliced data as an array of references and it should work as expected.

Example

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

const Thing = types.model({
  id: types.identifier
});

const RootStore = types
  .model({
    allData: types.array(Thing),
    sliced: types.maybe(types.array(types.reference(Thing)))
  })
  .actions((self) => ({
    setSliced() {
      const data = self.allData.slice(0, 20);
      self.sliced = data;
    }
  }));

const rootStore = RootStore.create({
  allData: Array.from({ length: 40 }, (_, index) => ({ id: index.toString() }))
});

console.log(rootStore.sliced); // undefined
rootStore.setSliced();
console.log(rootStore.sliced); // (20) [Object, Object, ...]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文