React js use Abort controller outside useEffect

1.6k Views Asked by At

I have a component where an abort controller is declared outside a useEffect. controller.abort() is called inside a useEffect when the component is unmounted.

When the component is unmounted this error below is thrown

Unhandled Rejection (AbortError): The operation was aborted.

 const controller = new AbortController()
    function MyComponent() {

      useEffect(() => {
        return () => controller.abort()
      }, [])
    
    const fetchData = async () => {
         try {
         const data = await fetchMyData(controller)
    } catch(error) {
    if (error.name === "AbortError") return
      console.log("Error ", error)
    }
  }
}

What am I doing wrong?

stacktrace images

enter image description here

2

There are 2 best solutions below

1
tanthuann On

Check your index.js in root. If you are using StrictMode, that is exactly the problem. Checkout document: https://reactjs.org/docs/strict-mode.html. I think what you should do here is call request and abort in the same one.

0
ihordoroshenko On

I tried all solutions from both of your tickets (this one and this of Unhandled Rejection (AbortError): The operation was aborted ). I tried Abortcontroller, cleanup after useEffect as well as try/catch, but it didn't come to the catch section at all. What worked for me was adding another catch in the try-area, basically, after the handling of the promise.

useEffect(() => {
    try {
      loadOptions()
        .then((response) => ...)
       // The error is catched here
        .catch((error) => console.log("Error"));
    } catch (error) {
      // It didn't work, as it never comes to this section
      console.log('Error ');
    }
  }, [item]);

So the error is catched and the app is not chashed. However, in my case, it is not really a good solution, as it seems to be a bug in new version of Apollo (as mentioned here DOMException: signal is aborted without reason in useEffect with async call ) and it should be handled more properly.