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

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

问题


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

const { proxy } = getCurrentInstance();  

报错信息:

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你确信返回的实例是非空的。在这种情况下,你可以使用非空断言!:

const { proxy } = getCurrentInstance()!;

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

const instance = getCurrentInstance();
if (instance) {
  const { proxy } = instance;
  // 现在你可以安全地使用 proxy
} else {
  console.error("无法获取组件实例");
}
相关文章
|
容器
Echarts报错 Cant read property getWidth of null的解决方案
Echarts报错 Cant read property getWidth of null的解决方案
185 0
【已解决】TypeError: Cannot destructure property `createHash` of ‘undefined‘ or ‘null‘
【已解决】TypeError: Cannot destructure property `createHash` of ‘undefined‘ or ‘null‘
477 1
|
7月前
|
消息中间件 Kubernetes Java
MQ产品使用合集之RocketMQ发消息失败了,proxy报connect to null failed如何解决
消息队列(MQ)是一种用于异步通信和解耦的应用程序间消息传递的服务,广泛应用于分布式系统中。针对不同的MQ产品,如阿里云的RocketMQ、RabbitMQ等,它们在实现上述场景时可能会有不同的特性和优势,比如RocketMQ强调高吞吐量、低延迟和高可用性,适合大规模分布式系统;而RabbitMQ则以其灵活的路由规则和丰富的协议支持受到青睐。下面是一些常见的消息队列MQ产品的使用场景合集,这些场景涵盖了多种行业和业务需求。
893 2
MQ产品使用合集之RocketMQ发消息失败了,proxy报connect to null failed如何解决
|
JavaScript API
【Vue】Cannot set reactive property on undefined,null,or primitive value:undefined
【Vue】Cannot set reactive property on undefined,null,or primitive value:undefined
386 0
|
Java 数据库连接 mybatis
There is no getter for property named ‘null‘ in ‘class
There is no getter for property named ‘null‘ in ‘class
191 0
There is no getter for property named ‘null‘ in ‘class
|
7月前
|
Java
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
166 1
|
Java 数据库连接 mybatis
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
2112 0
mybatis报错:Type handler was null on parameter mapping or property ‘__frch_xxx_0’
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
|
JavaScript
Uncaught TypeError: Cannot read property 'getItem' of null
Uncaught TypeError: Cannot read property 'getItem' of null
340 0
|
定位技术
调用百度报Cannot read property ‘lng‘ of null错误
调用百度报Cannot read property ‘lng‘ of null错误
调用百度报Cannot read property ‘lng‘ of null错误