未捕获(承诺中)TypeError:无法使用axios设置undefined的属性 [英] Uncaught (in promise) TypeError: Cannot set property of undefined with axios

查看:684
本文介绍了未捕获(承诺中)TypeError:无法使用axios设置undefined的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个vue.js组件,它使用axios检索joke对象的json数组:

I have this vue.js component that uses axios to retrive a json array of joke objects :

<template>
  <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
                <h2>{{joke.title}}</h2>
                <article>{{joke.body}}</article>
            <hr>
        </div>  

  </div>
</template>

<script>
import axios from 'axios';

    export default {
        name: 'showJokes',

      data () {
        return {
            jokes:[]

        }
      },

      methods: {

      },

      created() {
        axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){    
       //console.log(data); works fine
        this.jokes = data.body;
        });
    }
}
</script>

当我将结果记录到控制台中时,就可以了,但是当我尝试将其放入jokes数组中时,我得到了

When I log the result in console it's fine but when I try to put it in jokes array I get

未捕获(承诺)TypeError:无法设置以下属性的笑话" 未定义

Uncaught (in promise) TypeError: Cannot set property 'jokes' of undefined

这可能是一个微不足道的错误,但是作为vue.js的新手,我对此很感兴趣,因此感谢您的提示.

This may be a trivial error but as a newbie to vue.js I'm stock on this so appreciate your hints.

推荐答案

您不在this上下文中.您应该将this上下文存储在变量中.

You are out of this context. You should store this context on a variable.

 created() {
    let self = this
    axios.get('http://127.0.0.1:8090/api/jokes').then(function(data){    
   //console.log(data); works fine
    self.jokes = data.body;
    });
}

如何在回调中访问正确的this有很多方法? .您可以通过多种方式在这里参考.

There are many ways in How to access the correct this inside a callback? . You can refer here for many ways.

这篇关于未捕获(承诺中)TypeError:无法使用axios设置undefined的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆