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

Svelte组件中途切换时出现Cannot read properties of null (play)错误

解决Svelte打字效果组件卸载时的「Cannot read properties of null (play)」错误

错误根源是组件卸载后,定时器仍在后台运行,此时页面上的<audio>元素已被销毁,绑定的aud变量变为null,定时器回调里调用aud.play()就会触发报错。另外原代码里的clearInterval()没传定时器ID,根本无法停止定时器,这也是核心问题之一。

修复后的完整代码:

<script>
    import { onMount, onDestroy } from 'svelte'

    let phrase = "Head Admin Esports Middle East organization ( es.me website) and Project Manager at Arab Esports Website."
    let typedChar = "";
    let index = 0;
    let aud;
    let typingTimer; // 存储定时器ID,用于后续清除

    const typing = () => {
        typingTimer = setInterval(async () => {
            if (index < phrase.length) {
                typedChar += phrase[index];
                index++;
                // 调用play前先检查aud是否存在,避免元素销毁后报错
                if (aud) await aud.play();
            } else {
                clearInterval(typingTimer); // 传入定时器ID,正确停止定时器
            }
        }, 20)
    }

    onMount(() => {
        typing()
    })

    // 组件销毁时强制清除定时器,终止后台逻辑
    onDestroy(() => {
        if (typingTimer) clearInterval(typingTimer);
    })
</script>

<audio bind:this={aud} src={typingAudio} />

关键修改点:

  • 新增typingTimer变量保存定时器ID,确保能精准停止定时器
  • 通过onDestroy钩子在组件卸载时清除定时器,避免后台逻辑持续运行
  • 调用aud.play()前增加if (aud)判断,规避元素销毁后的空值调用
  • 修正clearInterval()传入定时器ID,解决原代码无法停止定时器的问题

内容的提问来源于stack exchange,提问作者Oliver Friedrich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:15:38