Property ‘proxy‘ does not exist on type ‘ComponentInternalInstance | null‘.ts

问题

Vue 3 使用 getCurrentInstance 获取当前正在执行的组件实例 TypeScript 报错。

typescript 复制代码
const { proxy } = getCurrentInstance();  

报错信息:

typescript 复制代码
Property 'proxy' does not exist on type 'ComponentInternalInstance | null'.ts

解决方案

在Vue 3的Composition API中,getCurrentInstance()返回的类型是ComponentInternalInstance | null。因此,当你使用const { proxy } = getCurrentInstance();时,TypeScript会报错,因为proxy属性在类型定义中并不存在。

为了解决这个问题,你可以使用类型断言(Type Assertion)来告诉TypeScript你确信返回的实例是非空的。在这种情况下,你可以使用非空断言!:

typescript 复制代码
const { proxy } = getCurrentInstance()!;

请注意,使用非空断言表示你确信getCurrentInstance()永远不会返回null。如果你不能确保这一点,最好在代码中进行适当的空值检查。例如:

typescript 复制代码
const instance = getCurrentInstance();

if (instance) {
  const { proxy } = instance;
  // 现在你可以安全地使用 proxy
} else {
  console.error("无法获取组件实例");
}
相关推荐
搏博16 分钟前
Hbuilder X4.65新建vue3项目存在的问题以及解决办法
前端·javascript·vue.js·ecmascript
Maya动画技术30 分钟前
ollama调用千问2.5-vl视频图片UI界面小程序分享
前端·python·计算机视觉·视觉检测
孩子 你要相信光1 小时前
vue3/vue2大屏适配
前端·javascript·vue.js
武昌库里写JAVA1 小时前
Iteration in Golang – How to Loop Through Data Structures in Go
java·vue.js·spring boot·学习·课程设计
xihaowen1 小时前
Android Edge-to-Edge
android·前端·edge
娃哈哈哈哈呀2 小时前
Vue 3 动态 ref 的使用方式(表格)
前端·javascript·vue.js
小妖6664 小时前
el-breadcrumb 面包屑第一项后面怎么写没有分隔符
javascript·vue.js·elementui
2401_896008194 小时前
GCC 使用说明
前端·javascript·算法
守城小轩8 小时前
JavaScript vs Python 用于 Web Scraping(2025):终极对比指南
前端·chrome·chrome devtools·指纹浏览器·浏览器开发·超级浏览器
风逸hhh10 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python