简体   繁体   中英

Cannot read properties of undefined (reading) in Vue3

I am getting this call from the famous ApiPokemon: https://pokeapi.co/api/v2/pokemon?limit=151

Once I have that data I want to pass it through another method ( _getPokemonData ) to map the complete data for each Pokémon.

However when I create this VueJS method I get this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_getPokemonData')

Why can't I call the _getPokemonData method inside the forEach? This is my code:

mounted() {
    this.$http
      .get("https://pokeapi.co/api/v2/pokemon?limit=151")
      .then((response) => {
        //this.pokemons = response.data.results;
        this.pokemons = response.data.results.forEach(function(pokemon){
          this._getPokemonData(pokemon); 
        });
      });

    this.$http
      .get("https://pokeapi.co/api/v2/type/")
      .then((response) => {
        this.types = response.data.results;
      });
  },

  methods: {
    _getPokemonData(pokemon) {
      console.log(pokemon);
    },

switch the function in forEach for a arrow function. by using 'function' you create a new scope which hijacks the 'this' reference.

see this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM