简体   繁体   中英

How to clean up function in a useffect call?

So i am updating state in a useEffect hook and getting this error i dont how to use cleanup function if we use async/await syntax in a useEffect hooks

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 %s.%s, a useEffect cleanup function,


  const getToken = async () => {
    const mytoken = await AsyncStorage.getItem("fb_token");
    if (mytoken) {
      navigation.navigate("Main", { screen: "Map" });
      setToken(mytoken);
    } else {
      setToken(false);
    }
  };
    getToken();

  }, [navigation]);```

How to update state and use clean up function should i declare this function outside hook but if i do that how would i use that function as a clean up?

You can get a callback when the component is unmounting or remounting as a result of one of the useEffect dependencies changing, by returning a function from useEffect . You can use that to set a flag to let yourself know things have changed. See *** comments:

useEffect(() => {
    let cancelled = false; // *** A flag to let us know this is cancelled

    const getToken = async () => {
        const mytoken = await AsyncStorage.getItem("fb_token");
        if (!cancelled) { // *** Check the flag
            if (mytoken) {
                navigation.navigate("Main", { screen: "Map" });
                setToken(mytoken);
            } else {
                setToken(false);
            }
        }
    };
    getToken().catch(error => {                 // ***
        // Handle/report error here...          // *** Handle errors from the async function
    });                                         // ***

    // *** A callback to let us know to set the flag
    return () => {
        cancelled = true;
    };
}, [navigation]);

(You're also breaking one of the rules of promises, flagged above: Always either handle errors, or pass the promise chain onto something that will.)

Note that as I mentioned earlier, that will skip setting the token in two situations:

  1. The component unmounted (the one that was causing you trouble)

  2. navigation changed

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