报错:类型“ComponentInternalInstance | null”上不存在属性“proxy”。ts(2339)

问题

在vue3+ts项目中,使用const { proxy } = getCurrentInstance()

报错:...类型"ComponentInternalInstance | null"

解决

既然会用到很多次getCurrentInstance()方法,索性直接封装一下

创建utils/useCurrentInstance.ts:

ts 复制代码
import { getCurrentInstance } from 'vue'
import type { ComponentInternalInstance } from 'vue'

export default function useCurrentInstance() {
  const instance = getCurrentInstance() as ComponentInternalInstance | null
  // 确保实例存在
  if (!instance) {
    throw new Error('useCurrentInstance must be used within a component setup')
  }

  const proxy = instance.appContext.config.globalProperties
  return {
    proxy
  }
}

使用时:

js 复制代码
import useCurrentInstance from '@/utils/useCurrentInstance'

const { proxy } = useCurrentInstance()
相关推荐
大怪v8 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习8 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健8 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒11 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat12 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
代码老中医12 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
不会敲代码112 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫12 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川12 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能
远山枫谷12 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序