Nuxt/TypeScript: Cannot access this - TS2339: Property 'XXX' does not exist on type

Viewed 2356

I have a problem using Nuxt.js with TypeScript. In my project I use dependencies like axios or nuxt-i18n. For this example I am using Axios. I configured it like in the documentation for nuxt/axios

nuxt.config.js

export default {
  modules: ['@nuxtjs/axios']
  axios: {},
}

tsconfig.json

{
  "compilerOptions": {
    "types": [
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  }
}

Now I want to use $axios in my Vuex store like this:

{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}

But now I get the error:

`TS2339: Property '$axios' does not exist on type '{ getIP(state: any, { commit }: { commit: any; }): Promise ; }'.`

Edit: The comments say, that using an arrow function should help. I tried it like this:

export const actions = {
  getIP: async ({commit}) => {
    const ip = await this.$axios.$get('http://icanhazip.com')
    ...
  }
};

but now the following error appears on "this."

TS7041: The containing arrow function captures the global value of 'this'.
1 Answers

After adding axios plug nuxt.config.js inside the plugins folder add axios-accessor.ts with the following content :

import { Plugin } from '@nuxt/types'
import { initializeAxios } from '~/utils/api'

const accessor: Plugin = ({ $axios }) => {
  initializeAxios($axios)
}

export default accessor

then create a folder named utils and inside it add the file api.ts :

import { NuxtAxiosInstance } from '@nuxtjs/axios'

let $axios: NuxtAxiosInstance

export function initializeAxios(axiosInstance: NuxtAxiosInstance) {
  $axios = axiosInstance
}
   
export { $axios }

In your store you could import the $axios like :

import { $axios } from '~/utils/api'

...

{
  actions: {
    async getIP ({ commit }) {
      const ip = await $axios.$get('http://icanhazip.com') //use $axios without this
      commit('SET_IP', ip)
    }
  }
}

For more details check this

Related