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
相关产品推荐
相关产品推荐

