Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

reactjs - How to fix the unmounted component in react hooks

How to fix the error: 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.

here' the code:

useEffect(() => {
        let ignore = false;
        setTimeout(() => {
            const fetchData = async () => {
                try {
                    setLoading(true);
                    setError({});
                    const response = await getLatest();
                    if (!ignore) setData(response['data']);
                } catch (err) {
                    setError(err);
                }
                setLoading(false);
            };
            fetchData();
        });
        return () => {
            ignore = true;
        };
    }, []);

The problem here is when I click the home page while loading the data and click the room page. then the error will appeared. How to fix on it?

question from:https://stackoverflow.com/questions/65912281/how-to-fix-the-unmounted-component-in-react-hooks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to clean up your timeout on unmount, otherwise, it tries to execute your hooks to update the internal state of the component after it goes out of scope (I assume functions like setLoading and setError are from a React hook).

To do so, put the output of setTimeout in a variable and then call clearTimeout in the function you return from useEffect. That's the clean up function and it's run when the component gets unmounted. So you need something like this:

React.useEffect(() => {
  ...
  const timeout = setTimeout(...)
  return () => {
    ...
    clearTimeout(timeout);
  }
}, [])

See the docs for more info: https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...