You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

离开页面时触发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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:54:58