简体   繁体   中英

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. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

which is usually happening when I am fetching data on component mount (in the 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. 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(); 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

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.

I encountered this when I fetching on client side I really recommend SWR for fetching on client side.

AbortController WebApi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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