离开页面时触发Cannot read properties of null (reading 'currentTime')错误但功能正常
问题解决:离开页面时触发
Cannot read properties of null (reading 'currentTime')错误 问题原因
离开页面(组件卸载)时,audioRef.current已变为null,但之前通过requestAnimationFrame注册的repeat回调仍在执行,尝试读取null的currentTime属性就会抛出该错误。
修复方案
1. 在回调中增加空值判断
访问audioRef.current属性前,先检查它是否存在:
const repeat = useCallback(() => { // 先判断audioRef.current是否有效 if (!audioRef.current) return; const time = audioRef.current.currentTime; setTimeProgress(time); progressRef.current.value = (time / duration) * 100; playAnimationRef.current = requestAnimationFrame(repeat); }, [audioRef, progressRef, duration]);
2. 组件卸载时取消动画帧
用useEffect在组件卸载时,取消已注册的动画帧,避免回调持续执行:
useEffect(() => { return () => { if (playAnimationRef.current) { cancelAnimationFrame(playAnimationRef.current); } }; }, [playAnimationRef]);
以上两步结合,就能彻底解决页面跳转时的报错,同时不影响原有功能。
内容的提问来源于stack exchange,提问作者Amin Ebadi
相关产品推荐
相关产品推荐

