[ACCEPTED]-How to fix React WArning : Can't perform a React state update on an unmounted component-anti-patterns

Accepted answer
Score: 10

In future version of React, you probably 22 won't need to fix this. As React dev team 21 is going to remove this warning in future 20 release. The main reason being this warning 19 can be false positive sometimes.

As per this 18 commit by Dan Abramov https://github.com/facebook/react/pull/22114

But what are the solutions 17 to fix this till that version release -

  1. Using 16 isMountState anti-pattern - If someone is 15 checking isMounted in his code to fix this 14 issue, then that person is already too late 13 in performing this check, as this warning 12 indicates the same check is done by React 11 and it failed.

  2. If this issue is because of 10 an asynchronous call. Then one possible 9 solution is to use AbortController API in 8 your code. AbortController API helps in 7 aborting any ajax call that is already made. Cool 6 stuff. Right?

More details on this can be 5 found here

Abort Controller1

So if it is a fetch API one can 4 use AbortController API like this

useEffect(() => {
  const abortController = new AbortController()
  // creating an AbortController
  fetch(url, {
      signal: abortController.signal
    })
    // passing the signal to the query
    .then(data => {
      setState(data)
      // if everything went well, set the state
    })
    .catch(error => {
      if (error.name === 'AbortError') return
      // if the query has been aborted, do nothing
      throw error
    })

  return () => {
    abortController.abort()
    // stop the query by aborting on the AbortController on unmount
  }
}, [])

If you 3 are using axios, then good news is axios 2 also provides support for AbortController 1 APIs -

const fetchData = async (params) => {
        setLoading(true);
        try {
            const result = await axios.request(params);
            // more code here 

        } catch (curError) {
            if (axios.isCancel(curError)) {
                return false;
            }
            // error handling code 
        }
        return null;
    };

    useEffect(() => {
        const cancelToken = axios.CancelToken;
        const source = cancelToken.source();

            fetchData({
                ...axiosParams,
                cancelToken: source.token
            });
        
        return () => {
            source.cancel("axios request cancelled");
        };
    }, []); 

More Related questions