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

Cannot read properties of undefined (reading 'destroy')报错如何修复

报错修复方案

报错根因

该错误属于典型的属性访问越界问题:你尝试访问video.parentElement.player的destroy方法时,video.parentElement.player本身是undefined,因此无法读取它的属性。

代码修复方式

方案1:加属性存在性判断(最通用,推荐)

使用可选链操作符?.逐层判断属性是否存在,不存在时直接中断访问,不会抛出错误,修改后代码如下:

const resetVideos = document.querySelectorAll(".exit");
resetVideos.forEach(function resetVideoHandler(video) {
  video.addEventListener("click", function resetVideoHandler() {
    // 逐层判断属性、方法存在后再执行
    video?.parentElement?.player?.destroy?.();
    console.log("hit")
  });
})

如果需要兼容不支持可选链的旧版本浏览器,可以换成逐层手动判断的写法:

const resetVideos = document.querySelectorAll(".exit");
resetVideos.forEach(function resetVideoHandler(video) {
  video.addEventListener("click", function resetVideoHandler() {
    if (
      video.parentElement && 
      video.parentElement.player && 
      typeof video.parentElement.player.destroy === 'function'
    ) {
      video.parentElement.player.destroy();
    }
    console.log("hit")
  });
})

方案2:优化事件绑定时机

如果player对象是点击play svg元素之后才初始化挂载到父元素上的,可以把exit按钮的点击事件绑定逻辑放到player初始化完成的回调函数中,确保事件触发时player一定存在。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:15:03