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])
推荐阅读
-
关于MySQL时常闪退的问题解决办法分享(图)
-
react-three-fiber 加载 obj / gltf 格式的文件
-
React hooks-useEffect | 解决报错Warning...cancel all subscriptions and asynchronous tasks in a useEffect
-
Oracle错误ORA-01950对表空间"system"无权限解决
-
stop-and-remove-all-docker-containers-and-images
-
ubuntu下的火狐浏览器无法播放视频解决方案
-
关于 iOS 的 WebView 播放视频/音频无法停止的解决方案
-
解决springmvc不能直接访问 jsp的问题
-
Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?
-
React hook 报错Warning...cancel all subscriptions and asynchronous tasks in a useEffect cleanup fn