Vue3错误处理器中如何获取组件完整状态或转换实例为普通对象
问题
我使用Vue3 Composition API搭配Bugsnag做错误处理,希望报错时把出错组件的完整状态(即setup函数返回的对象)上报给Bugsnag。
当前代码如下:
app.config.errorHandler = (error, instance, info) => { Bugsnag.notify(error, function (event) { event.addMetadata('instance', {...instance}) }) }
本地运行正常,但控制台会弹出警告:
"Avoid app logic that relies on enumerating keys on a component instance. The keys will be empty in production mode to avoid performance overhead."
且生产环境中获取的对象为空。核心需求是:如何在Vue错误处理器中正确获取包含所有属性的组件状态?
示例场景的组件代码:
<div id="app"> <example></example> </div>
const app = Vue.createApp({}) app.config.errorHandler = (error, instance, info) => { console.log({...instance}) } app.component('example', { template: ` <div> <button @click="nonExistentThing()"> Create Error </button> </div> `, props: { testprop: { type: String, default: 'foobar' } }, setup() { const hello = 'hello world' return {hello} } }) app.mount('#app')
本地能输出预期内容但带警告:
{ "testprop": "foobar", "hello": "hello world" }
期望拿到的结构示例:
{ "props": {"testprop": "foobar"}, "data": {"hello": "hello world"} }
解决方案
方法1:直接访问组件内置属性
Vue组件实例提供了$props和$data两个安全的内置属性,可直接获取对应内容,不会触发生产警告,且生产环境有效:
app.config.errorHandler = (error, instance, info) => { const componentState = { props: {...instance.$props}, data: {...instance.$data} } Bugsnag.notify(error, function (event) { event.addMetadata('componentState', componentState) }) }
$props:包含组件所有接收的props(包括默认值)$data:包含setup函数返回的所有响应式属性,以及Options API中data选项的内容
方法2:自定义状态收集钩子(更灵活)
如果需要过滤敏感数据或只收集关键状态,可以在组件内定义自定义方法,再在错误处理器中调用:
- 组件内添加状态收集方法:
app.component('example', { // ... 其他配置 setup(props) { const hello = 'hello world' // 自定义状态收集函数 const getComponentState = () => ({ props: {...props}, data: {hello} }) // 将方法挂载到组件实例 return {hello, getComponentState} } })
- 错误处理器中调用该方法:
app.config.errorHandler = (error, instance, info) => { let componentState = {} if (instance.getComponentState) { componentState = instance.getComponentState() } Bugsnag.notify(error, function (event) { event.addMetadata('componentState', componentState) }) }
注意事项
- 禁止直接解构整个组件实例(
{...instance}),这正是警告和生产环境失效的根源——Vue在生产环境会隐藏实例的可枚举属性以优化性能。 - 组件中使用
ref或reactive创建的响应式值,会自动包含在$data中,无需额外处理。
内容的提问来源于stack exchange,提问作者John Mellor
相关产品推荐
相关产品推荐

