SoFunction
Updated on 2025-03-02

Can't perform a React state update on an unmounted component error report solution

Overview

To solve"Warning: Can't perform a React state update on an unmounted component", can be in youruseEffectDeclare a hookisMountedBoolean value, used to track whether the component is installed. The state of a component will only be updated when the component is mounted.

import {useState, useEffect} from 'react';
const App = () => {
  const [state, setState] = useState('');
  useEffect(() => {
    // 👇️ set isMounted to true
    let isMounted = true;
    async function fetchData() {
      const result = await (['hello', 'world']);
      // 👇️ only update state if component is mounted
      if (isMounted) {
        setState(result);
      }
    }
    fetchData();
    return () => {
      // 👇️ when component unmounts, set isMounted to false
      isMounted = false;
    };
  }, []);
  return (
    <div>
      <h2>State: {(state)}</h2>
    </div>
  );
};
export default App;

When we try to update the state of an unmounted component, a warning appears that "Cannot perform React status updates on unmounted components".

isMounted

The straightforward way to get rid of that warning is,useEffectUsed in hooksisMountedBoolean value to track whether the component is mounted.

existuseEffectIn, we initializeisMountedThe boolean value istrue

OurfetchDataFunctions perform some asynchronous tasks, most commonly an API request, and update the status according to the response.

However, it should be noted that we only haveisMountedThe variable is set totrueThe status will be updated only when .

async function fetchData() {
  const result = await (['hello', 'world']);
  // 👇️ only update state if component is mounted
  if (isMounted) {
    setState(result);
  }
}

This helps us avoid warnings because if the component is not mounted, we will not update the state.

When the component is uninstalled,useEffectThe function returned by the hook will be called.

return () => {
  // 👇️ when component unmounts, set isMounted to false
  isMounted = false;
};

We set upisMountedThe variable isfalse, means that the component is no longer mounted. iffetchDataThe function is called when the component is uninstalled.ifThe code block won't execute becauseisMountedSet asfalse

async function fetchData() {
  const result = await (['hello', 'world']);
  // 👇️ only update state if component is mounted
  if (isMounted) {
    setState(result);
  }
}

extract

If you do this frequently, you can extract the logic into a reusable hook.

import {useState, useEffect, useRef} from 'react';
// 👇️ extract logic into reusable hook
function useIsMounted() {
  const isMounted = useRef(false);
  useEffect(() => {
     = true;
    return () => {
       = false;
    };
  });
  return isMounted;
}
const App = () => {
  const [state, setState] = useState('');
  // 👇️ use hook
  const isMountedRef = useIsMounted();
  useEffect(() => {
    async function fetchData() {
      const result = await (['hello', 'world']);
      // 👇️ only update state if component is mounted
      if () {
        setState(result);
      }
    }
    fetchData();
  }, [isMountedRef]);
  return (
    <div>
      <h2>State: {(state)}</h2>
    </div>
  );
};
export default App;

useRef()The hook can pass an initial value as an argument. The hook returns a mutable ref object whose.currentThe attribute is initialized as the passed parameter.

We're inuseIsMountedThe hook tracks whether the component is mounted, just like we directly on the component'suseEffectIt's done in the hook.

It should be noted that infetchDataIn the function, we must checkvalue, becauserefOncurrentThe attribute isrefThe actual value of .

Translation link:/blog/react-…

The above is the detailed content of the solution to the error report of Can't perform a React state update on an unmounted component. For more information about the error report of React state update, please follow my other related articles!