简体   繁体   English

在 ReactJs useEffect 中使用 AbortController 和 useStateIfMounted

[英]Using AbortController and useStateIfMounted in ReactJs useEffect

In my code, I am getting the warning在我的代码中,我收到了警告

Warning: Can't perform a React state update on an unmounted component.警告:无法对未安装的组件执行 React state 更新。 This is a no-op, but it indicates a memory leak in your application.这是一个空操作,但它表明您的应用程序中存在 memory 泄漏。 To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.要修复,请取消 useEffect 清理中的所有订阅和异步任务 function。

which is usually happening when I am fetching data on component mount (in the useEffect).这通常发生在我在组件挂载上获取数据时(在 useEffect 中)。 After doing some research, I found that it's due to a change of component while the previous component was still executing the process on component mount and didn't cleanup.研究了一下,发现是因为组件发生了变化,而之前的组件还在执行组件挂载的过程,并没有进行清理。

I found that using我发现使用

useEffect(()=>{
let abortController = new AbortController();  
//function here
return () => {  
abortController.abort();  
    } 
},[]); 

fixes the issue since the abortController.abort() aborts everything on DOM change.解决了这个问题,因为 abortController.abort() 中止了 DOM 更改的所有内容。 But I do not know how safe it is or if it has any side effects if I am to add it to my code.但我不知道它有多安全,或者如果我将它添加到我的代码中是否有任何副作用。

I found another method which involves using useStateIfMounted() instead of useState();我发现了另一种涉及使用 useStateIfMounted() 而不是 useState() 的方法; however, I we are in the later stages in the project and we are kind of scared that this might cause the website to crash in some way.然而,我们正处于项目的后期阶段,我们有点害怕这可能会导致网站以某种方式崩溃。

Which method is better and is there another method to fix this error?哪种方法更好,还有另一种方法可以修复此错误吗?

I have a suggestion use SWR REACT HOOK DATA FETCHER我有一个建议使用SWR REACT HOOK DATA FETCHER

it's because AbortController is finding his signal I think you did not put his signal on fetcher if you are using axios -> axios(url,{signal:abortController.signal}) you are getting that error cause you only made new abortController without putting his signal to a fecher and he don't know what data he will prevent from requesting.这是因为 AbortController 正在找到他的信号我认为如果你使用 axios -> axios(url,{signal:abortController.signal})你没有把他的信号放在 fetcher 上你会收到那个错误因为你只制作了new abortController而没有把他的向 fecher 发出信号,他不知道他会阻止请求什么数据。

I encountered this when I fetching on client side I really recommend SWR for fetching on client side.我在客户端获取时遇到了这个问题,我真的推荐 SWR 在客户端获取。

AbortController WebApi 中止控制器 WebApi

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

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