onUnmounted 报错anchor.vue:45 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'removeEventListener')
时间: 2023-10-19 09:01:51 浏览: 184
根据提供的引用内容,问题中的错误是在离开当前页面时,使用了onUnmounted钩子函数导致的。报错信息显示在anchor.vue文件的第45行,错误类型为TypeError: Cannot read properties of null (reading 'removeEventListener')。
这个错误可能是因为在组件销毁时,试图从一个空值(null)中读取属性。这是因为在组件销毁之前,尝试移除一个事件侦听器,但是该事件侦听器可能在销毁之前已经被移除或设置为null。
为了解决这个问题,可以在onUnmounted钩子函数内部添加一个条件判断,确保只在事件侦听器存在时才尝试移除它。这样可以避免在已经移除或设置为null的事件侦听器上尝试移除操作,从而避免报错。例如可以使用以下代码:
onUnmounted(() => {
if (window) {
window.removeEventListener('resize', this.initEchart, 20);
}
});
这样,当组件销毁时,只有在窗口对象存在时,才会尝试移除resize事件的侦听器。通过这样的条件判断,可以避免在销毁过程中发生错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [vue项目报错Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ...](https://blog.csdn.net/A535366/article/details/122358556)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [vue项目报错Uncaught (in promise) TypeError Cannot read properties of undefined (reading ...](https://blog.csdn.net/m0_67401545/article/details/123373591)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文