报错:类型“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()
相关推荐
九酒15 分钟前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
Jackson__1 小时前
做了一段时间的AI coding后,我终于搞清了 CLI 和 MCP 的区别
前端·agent·ai编程
IT_陈寒3 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569154 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔5 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6876 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen7 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding9 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693559 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill9 小时前
curl命令学习笔记一
前端