Tag Archives: Vue3 ts setup getCurrentInstance

How to Solve Vue3 ts setup getCurrentInstance Error

environment

vscode

typescript4

vue3

Problem description

First of all, the configuration of global variables and methods in vue3 is different from that in vue2. If you are not clear, you can check the official instructions, but you encounter problems when using them in combination with typescript :

axios.ts

// axios.ts
import axios from 'axios'
const app = Vue.createApp({})

// Global Custom Properties
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

app.config.globalProperties.$axios = axios

Any Vue file

<script lang="ts" setup>
import { getCurrentInstance } from 'vue';

// First, here the proxy ts will report
// Property "proxy" does not exist on type "ComponentInternalInstance | null". ts(2339)
const { proxy } = getCurrentInstance()

// Then this error will be reported below
// Unsafe member access .$axios on an `any` value.  eslint@typescript-eslint/no-unsafe-member-access
// Unsafe call of an `any` typed value.  eslint@typescript-eslint/no-unsafe-call
proxy.$axios('')

The above is the whole content of error reporting. Next, let’s solve this problem

Problem-solving:

The first error is easy to understand. Because the return type of getcurrentinstance() has null, you can add assertions here

import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// Add Assertion
const { proxy } = getCurrentInstance() as ComponentInternalInstance

2. However, after the correction, we found that there are still errors reported below

// Object may be "null".ts(2531)
proxy.$axios('')

This problem is easier to solve. Add after proxy to filter the results of null

proxy?.$axios('')

Above, the problem is solved!