To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

后端 未结 6 915
无人及你
无人及你 2021-02-03 23:18

I have this code

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route         


        
6条回答
  •  旧时难觅i
    2021-02-03 23:39

    I think the problem is caused by dismount before async call finished.

    const useAsync = () => {
      const [data, setData] = useState(null)
      const mountedRef = useRef(true)
    
      const execute = useCallback(() => {
        setLoading(true)
        return asyncFunc()
          .then(res => {
            if (!mountedRef.current) return null
            setData(res)
            return res
          })
      }, [])
    
      useEffect(() => {
        return () => { 
          mountedRef.current = false
        }
      }, [])
    

    mountedRef is used here to indicate if the component is still mounted. And if so, continue the async call to update component state, otherwise, skip them.

    This should be the main reason to not end up with a memory leak (access cleanedup memory) issue.

提交回复
热议问题