报错:Warning: Can't perform a React state update ...

来源:6-7 本章总结

慕尼黑0536602

2022-04-13

Hi 老师,
我下面代码出现了这个报错。。

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.


您可以帮我看下要怎么修改吗?谢谢

import { useIsFocused } from '@react-navigation/native';
const [token,setToken] = useState('');
const isFocused = useIsFocused();
    const getMe = async () =>{
      await storage.getToken().then(token=>setUserToken(token));
   }
    useEffect(()=>{
      getMe();
      fetch(`${baseUrl}/userInfo/getMe`,{
        method : "get",
        headers :new Headers({
          'Content-Type':'application/json',
          "Authorization": `Bearer ${userToken}`
         }),
       }).then(res=>res.json()).catch(error=>console.log(error))

    },[isFocused]);
写回答

1回答

CrazyCodeBoy

2022-04-13

问题的原因在于:你在异步设置setUserToken的时候,当前组件已经卸载了导致的。

解决方案是:当更新state的时候检测组件是否有卸载,如果已经卸载则不执行更新state操作。

import { useIsFocused } from '@react-navigation/native';
const [token,setToken] = useState('');
const isFocused = useIsFocused();
  let unmounted = false;//组件是否有卸载
    const getMe = async () =>{
      await storage.getToken().then(token=>{
        //如果没有被卸载才更新
        if(!unmounted) setUserToken(token)
      });
   }
    useEffect(()=>{
      getMe();
      fetch(`${baseUrl}/userInfo/getMe`,{
        method : "get",
        headers :new Headers({
          'Content-Type':'application/json',
          "Authorization": `Bearer ${userToken}`
         }),
       }).then(res=>res.json()).catch(error=>console.log(error))
       return () => {
        unmounted = true;
      };
    },[isFocused]);


1
1
慕尼黑0536602
好的,谢谢老师
2022-04-14
共1条回复

RN入门到进阶,打造高质量上线App

解锁React Native开发应用新姿势,React Native新版本热门技术

3144 学习 · 3241 问题

查看课程