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("无法获取组件实例");
}
相关推荐
奔跑的web.9 小时前
TypeScript Enum 类型入门:从基础到实战
前端·javascript·typescript
盐真卿9 小时前
python2
java·前端·javascript
梦梦代码精9 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
刘一说9 小时前
Vue3 组合式 API(Composition API):逻辑复用的革命性实践
vue.js·vue
seabirdssss10 小时前
《bootstrap is not defined 导致“获取配置详情失败”?一次前端踩坑实录》
前端·bootstrap·html
kgduu10 小时前
js之表单
开发语言·前端·javascript
谢尔登12 小时前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码12 小时前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
欣然~14 小时前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python
一个小废渣14 小时前
Flutter Web端网络请求跨域错误解决方法
前端·flutter