Subscribe on changes!

getCurrentInstance returns null after await

avatar
Oct 31st 2023

Vue version

3.3.7

Link to minimal reproduction

https://play.vuejs.org/#eNp9UttqwkAQ/ZXpviSCVVrfJApVhFrohbbQlwUJcYyxm91lL2oJ+fdONqgVrA8hO3POzJwzuxV70Lq39ciGLLGZKbQDi87rMZdFqZVxUIHBVRdydFNvDEo3l9alMsMuKDnBlTL4rLx0UMPKqBIi6hZxyWWmiAilzWHUtIijRxRCwZcyYnkTdU6UpVpYVaJbFzJf2B+ZUUEa/nEHRmOoai7PRsVnKJcATSMlsCdUHkd30SW5cYdGAqS7tLgwMg7gWZv7/9vU9CX9dl+0KQocllqkDikCSNZ346oK1us66VMUsoXU3sH2tlRLFCPOCOeMoKR/rGZd5iypWBV5b2OVpGsJ/jjLVKkLgeZVu4JUcjZsnTdYSnvdPYWcMx67h3y2xuz7Qn5j902OszeDFs0WOTtiLjVkuoVnHy+4p/MRJOVeEPsK+I60Qd9obGkTL5ck+w8vqJ2Hx0Xb/7SzvUNpD6YaoQ2zDnzO6DVNr1g/yR30BqGObofVvx7q9YA=

Steps to reproduce

<script setup>
import { ref, getCurrentInstance, onBeforeMount } from 'vue'

const msg = ref('Hello World!')

const do_something_sync = async () => {}
onBeforeMount(async () => {
  console.log('1', getCurrentInstance())
  await do_something_sync()
  console.log('2', getCurrentInstance())
})
</script>

<template>
  <h1>{{ msg }}</h1>
  <input v-model="msg">
</template>

What is expected?

getCurrentInstance should return ComponentInternalInstance object

What is actually happening?

getCurrentInstance returns null after await

System Info

No response

Any additional comments?

No response

avatar
Oct 31st 2023

This is intended. You should cache the instance before awaits.

avatar
Oct 31st 2023

You should use getCurrentInstance in the setup to save the current instance to a variable. If asynchronously retrieved, it works similarly to watchEffect in not collecting asynchronous dependencies.