Vue.js出现TypeError: Cannot read properties of undefined (reading '$refs')报错原因咨询
报错原因
- 组件未完成渲染/挂载就触发调用:
$refs只有在对应组件完成挂载渲染后才会被填充,如果你在父组件created生命周期、或者子组件被v-if控制且调用时条件未生效、或者页面初始加载还没完成子组件渲染就触发了这串调用逻辑,对应层级的组件实例不存在,读取$refs就会抛出该错误。 - 多层嵌套ref的时序不稳定:你的代码用了3~4层嵌套
$refs,父组件只能保证自身直接子组件(也就是第一层patientinputmask)的挂载时机,子组件内部的$refs由子组件自身的渲染周期决定,父组件无法保证调用时子组件内部的ref已经初始化完成。 - 异步操作触发组件销毁/重渲染:你调用的方法都是异步的,若前一个
await执行过程中触发了路由跳转、组件v-if切换、列表重渲染等逻辑,会导致后续调用依赖的某层组件被销毁,对应的$refs就会变成undefined。 - 调用过程中父组件已销毁:如果触发这串调用后用户快速切换页面/关闭弹窗,父组件实例已经被销毁,后续执行的异步逻辑拿不到正确的
this.$refs也会报该错误。
临时修复方案
你可以在调用前加可选链操作符判空,避免整个调用链路中断:
await this.$refs.patientinputmask?.$refs.patientpersonaldata?.ChangePersonalData?.(); await this.$refs.patientinputmask?.$refs.patientaddressdata?.SavePersonalAddressObject?.(); await this.$refs.patientinputmask?.$refs.patientbankaccountdata?.SavePersonalBankAccountObject?.(); await this.$refs.patientinputmask?.$refs.patientrelatedcontacts?.SaveRelatedContactObject?.(); if (this.invoiceHN == true) { await this.$refs.patientinputmask?.$refs.invoicedata?.$refs.invoiceHN?.$refs.invoiceKasseHeaderHN?.SavePatientDataForInvoice?.(); await this.$refs.patientinputmask?.$refs.invoicedata?.$refs.invoiceHN?.$refs.invoicingTemplateHN?.SavePatientTemplateConfigDTO?.(); }
长期优化建议
避免多层嵌套$refs调用,改用事件总线、Pinia/Vuex状态管理、或者父组件传递props触发子组件内部执行对应逻辑的方式实现,彻底规避ref时序问题。
内容的提问来源于stack exchange,提问作者Daniel Rauch
相关产品推荐
相关产品推荐

