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("无法获取组件实例");
}
相关推荐
DIKKOO13 小时前
React 19 修复了一个遗留多年的类型乌龙,过程竞如此曲折
前端·react.js
程序员爱钓鱼13 小时前
Node.js 编程实战:Node.js + React Vue Angular 前后端协作实践
前端·后端·node.js
程序员爱钓鱼13 小时前
Node.js 编程实战:前后端结合的 SSR 服务端渲染
前端·后端·node.js
haokan_Jia13 小时前
Java 并发编程-ScheduledFuture
java·前端·python
bst@微胖子13 小时前
CrewAI+FastAPI实现多Agent协作项目
java·前端·fastapi
掘金酱13 小时前
TRAE 2025 年度报告分享活动|获奖名单公示🎊
前端·人工智能·后端
jqq66613 小时前
解析ElementPlus打包源码(三、打包类型)
前端·javascript·vue.js
白哥学前端14 小时前
独立开发实战:我用 AI 写了一个台球小程序
前端·后端·trae
陳陈陳14 小时前
React 性能优化双子星:useMemo 与 useCallback 的正确打开方式
前端·javascript·react.js
持续前行14 小时前
JavaScript 数组中删除偶数下标值的多种方法
前端·javascript·vue.js