Static GitHub Issues

[1630] [BUG] Unable to use `this` inside `asyncData`

prev: can't run bash script after production build
next: if data is undefined: app goes out of sync on SPA

I have a component like this:

<template>
  <div>
    <some-component :user="user"></some-component>
  </div>
</template>

<script>
  import SomeComponent from '@/components/some-component'
  import fetch from 'isomorphic-fetch'

  export default {
    components: {
      'some-component': SomeComponent,
    },

    mounted() {
      console.log(' 1 route name:', this.$route.path) // this works fine.
    },

    async asyncData(...args) {
      console.log(' 2 args:', args)
      console.log(' 2 this:', this) // UNDEFINED
      console.log(' 2 route name:', this.$route.path) // ERROR, cannot read property $route of undefined.

      const json = await (
        await fetch(`/api${this.$route.path}`)
      ).json()

      console.log(' -- json', json)

      return json
    },
  }
</script>

And when it gets to the line with console.log(' 2 route name:' it throws an error that this is undefined.

<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1456">#c1456</a>)</em></sub></div>