reactjsmobxmobx-state-tree

Cannot add an object to a state tree if it is already part of the same or another state tree


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?


Solution

  • 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, ...]