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])

 

你可能感兴趣的:(react)