简体   繁体   English

循环检测到@computed 属性的错误

[英]Cycle detected error for @computed properties

I'm just a beginner in MobX.我只是 MobX 的初学者。 I was trying out the computed properties in MobX and ran into this error我正在尝试 MobX 中的计算属性并遇到此错误

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

I created a store class with an observable computed property.我创建了一个具有可观察计算属性的商店 class。 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.我看到一堆 github 问题是针对相同的错误消息打开的,但它们都是针对非常具体的情况。 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.我在这个链接中做了一个非常简单的用例,可以重现这个错误。

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.您有 2 个具有相同名称values的 class 字段,一个是observable的,另一个是computed的,您不能同时使用它们并且实际上不需要它们。

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. computed用于计算东西(嗯,duh)或从另一个observable派生一些值。 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更多文档https://mobx.js.org/refguide/computed-decorator.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM