Home

Issue: 1630

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

[issue link]

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.

This question is available on Nuxt.js community (#c1456)