TypeError: Cannot set properties of undefined (setting ‘xx‘)的问题及解决方法

 更新时间:2023年09月13日 09:42:29   作者:FBI HackerHarry浩  
这篇文章主要介绍了TypeError: Cannot set properties of undefined (setting ‘xx‘)的问题,本文给大家分享完美解决方案,需要的朋友可以参考下

TypeError: Cannot set properties of undefined (setting ‘xx‘) 

问题描述

我在编写axios请求后端数据的时候,一直出现下面的错误前端页面显示不出来。

报错:

TypeError: Cannot set properties of undefined (setting ‘xx’)

原因分析:

this指向的对象发生了变化(现在this代表axios对象),需要在函数前将this指向的对象提前保存一下

解决方案:

方法一:回调函数使用箭头函数来使用。(responde)=>{}

<template>
    <el-table :data="tableData" style="width: 100%" stripe>
        <el-table-column prop="name" label="姓名"  width="250" />
        <el-table-column prop="age" label="年龄" width="250" />
        <el-table-column prop="gender" label="性别" width="250" />
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column fixed="right" label="操作" width="250">
            <template #default>
                <el-button link type="primary" size="small">编辑</el-button>
                <el-button link type="primary" size="small">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>
<script>
    import axios from 'axios';
    export default {
        data() {
            return {
                tableData:[]
            }
        },
        created(){//为何 要在created 方法中 发请求,因为该方法 可以操作tableData属性
            // 解决方法一
            axios.get('http://localhost:9090/student') // url 请求后台的地址
                /*
                * .then(function (response) 这样写前端会报错
                * 报错信息:TypeError: Cannot set properties of undefined (setting 'tableData')at eval (Student.vue?401d:59:1)
                * 这样写是匿名函数,无法取到tableData的值,所以tableData的值为undefined,不能给undefined的变量赋值
                * 解决办法:1.改为箭头函数 2.将this重新赋值给新的变量
                */
                // .then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
                .then(response=> { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
                    console.log(response);
                    console.log(response.data)
                    this.tableData = response.data;
                })
                .catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
                    console.log(error);
                });
        },
        methods:{
        }
    }
</script>

方法二:暂存this。var th = this; 在内部用th.xx代替this.xx

   //解决办法二
        var th = this;
        axios.get('http://localhost:9090/student') // url 请求后台的地址
            .then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
                console.log(response);
                console.log(response.data)
                th.tableData = response.data;
            })
            .catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
                console.log(error);
            });

到此这篇关于TypeError: Cannot set properties of undefined (setting ‘xx‘)的文章就介绍到这了,更多相关Cannot set properties of undefined内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论