Cycle detected error for @computed properties

Viewed 1255

I'm just a beginner in MobX. I was trying out the computed properties in MobX and ran into this error

[mobx] Cycle detected in computation Store@1.values: function () {
  initializeInstance(this);
  return this[prop];
}

I created a store class with an observable computed property. When I tried to use it in a react functional component, it gave me this error. I saw a bunch of github issues that were opened for the same error message but they were all for very specific cases. I understood that it is because the value of the computed property is being accessed before it has been computed at least once. What I could not figure out is how to avoid this situation. I have made a very simple usecase in this link where this error can be reproduced.

1 Answers

You have 2 class fields with the same name values, one is observable, another is computed, you can't use both of them and you actually don't need both of them.

export default class Store {
  @observable values; // <--- Not needed

  constructor() {
    this.selectedFilters = {};
    this.assetMap = {};
    this.searchResults = {};
  }

  @computed get values() {
    return [{}];
  }
}

computed is used to compute stuff (well, duh) or derive some values from another observable's. For example, you could use it like that

export default class User {
  @observable name = 'John'; 
  @observable lastName= 'Doe'; 

  @computed get fullName() {
    return this.name + this.lastName
  }
}

Or in your case something like this could be useful

export default class Store {
  @observable values = []

  @computed get filteredValues() {
    return this.values.filter(someFilterFunction);
  }
}

More in the docs https://mobx.js.org/refguide/computed-decorator.html

Related