Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用相同的依赖项值调用useEffect两次-依赖项是可观察的mobx属性_Reactjs_Dependencies_Use Effect_Mobx React - Fatal编程技术网

Reactjs 使用相同的依赖项值调用useEffect两次-依赖项是可观察的mobx属性

Reactjs 使用相同的依赖项值调用useEffect两次-依赖项是可观察的mobx属性,reactjs,dependencies,use-effect,mobx-react,Reactjs,Dependencies,Use Effect,Mobx React,我有一个react组件,它使用useEffect和mobx状态的依赖关系: useEffect((): (() => void) => { console.log(appState.getCurrent()); }, [appState.getCurrent()]); @observable private current = {} as any; @action public setCurrent(c: any) { this.current = c; } @comp

我有一个react组件,它使用useEffect和mobx状态的依赖关系:

useEffect((): (() => void) => {
  console.log(appState.getCurrent());
}, [appState.getCurrent()]);
@observable private current = {} as any;

@action public setCurrent(c: any) {
  this.current = c;
}

@computed public getCurrent() {
  return this.current;
}
mobx状态下的相关代码:

useEffect((): (() => void) => {
  console.log(appState.getCurrent());
}, [appState.getCurrent()]);
@observable private current = {} as any;

@action public setCurrent(c: any) {
  this.current = c;
}

@computed public getCurrent() {
  return this.current;
}
非常奇怪,但是使用相同的值调用了两次useEffect。
正在调试setCurrent方法,它只被调用一次。
更奇怪的是,我试图将依赖项更改为appState.getCurrent().id,但它仍然使用相同的值获得了两次useEffect。
这可能是因为使用mobx属性作为useEffect的依赖项吗?
如何解决此问题?

您必须使用,如文档所示

useEffect((): (() => void) => {
  autorun(reaction)=>{
    console.log(appState.getCurrent());
  }
  
}, []);