天天看點

React hooks-useEffect | 解決報錯Warning...cancel all subscriptions and asynchronous tasks in a useEffect

const [isMobile, setIsMobile] = useState(false)
  useEffect(() => {
    window.onresize = () => {
      document.documentElement.clientWidth < 760
        ? setIsMobile(true)
        : setIsMobile(false)
      console.log('resize')
    }
  }, [setIsMobile])
           

比如這裡,使用useEffect注冊了一個監聽視窗大小的函數,但是,當切換其他元件時,react報錯

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. in About

提示記憶體洩漏,需要在元件内取消訂閱。

解決辦法,useEffect的第一個參數應該傳回一個函數,用來取消事件監聽。

const [isMobile, setIsMobile] = useState(false)
  useEffect(() => {
    window.onresize = () => {
      document.documentElement.clientWidth < 760
        ? setIsMobile(true)
        : setIsMobile(false)
      console.log('resize')
    }
    return () => {
      window.onresize = null
      console.log('resize:clear')
    }
  }, [setIsMobile])