簡體   English   中英

修復 Can't perform a react state update on an unmounted component React native

[英]Fix Can't perform a react state update on an unmounted component React native

如何在我的本機反應中修復此錯誤,請參閱下面的代碼。

警告:無法對未安裝的組件執行 React state 更新。 這是一個空操作,但它表明您的應用程序中存在 memory 泄漏。 要修復,請取消 useEffect 清理中的所有訂閱和異步任務 function。

   const getData = () => {
        setIsLoading(true)
        axios.get(hosturl.loaduser + userlist.user_id + '&page=' +currentPage)
        .then((response) => {
            setEvent([...userData, ...response.data.data])
            setIsLoading(false)
        })
    }
  
    useEffect(() => {    
        getData();
    }, [currentPage]);

我做了類似下面的事情,但錯誤不斷出現。

useEffect(() => {   
    let isMounted = true;    
    if (isMounted) getData();    
    return () => { isMounted = false }; 
}, [currentPage]);
function MyComponent() {
    const mounted = useRef(false);

    const getData = () => {
      setIsLoading(true)
      axios.get(hosturl.loaduser + userlist.user_id + '&page=' +currentPage)
        .then((response) => {
          if (mounted.current) {
            setEvent([...userData, ...response.data.data])
            setIsLoading(false)
          }
        })
     }

    useEffect(() => {
        mounted.current = true;
        return () => {
            mounted.current = false;
        };
    }, []);

    useEffect(() => {     
      if (mounted.current) {
        getData();    
      }
    }, [currentPage]);

    return (
        ...
    );
}

useEffect()鈎子應該處理mounted的引用,在掛載組件並將可變的mounted.current值設置為 true 時調用。 當卸載組件並將mounted.current值設置為false時,會調用useEffect()掛鈎的返回值 function。

之后你可以使用mounted的 ref(它就像舊式 class 組件中的成員變量)。 即僅當您的組件已安裝時才能獲取您的數據,或者僅當組件已安裝時才在回調中設置 state。

您可以使用 axios 取消:

const controller = new AbortController();

const getData = () => {
   setIsLoading(true)
   axios.get(hosturl.loaduser + userlist.user_id + '&page=' +currentPage, {
    signal: controller.signal
   }).then((response) => {
       setEvent([...userData, ...response.data.data])
       setIsLoading(false)
    })
}
  
 useEffect(() => {    
    getData();
    
    return () => {
        controller.abort();
    };
 }, [currentPage]);

通過這種方式,您將中止 axios get on component unmount,避免setEventsetIsLoading (然后是警告)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM