欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

React hooks-useEffect | 解决报错Warning...cancel all subscriptions and asynchronous tasks in a useEffect

程序员文章站 2023-12-30 19:21:16
...
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])

 

上一篇:

下一篇: