TypeError: Cannot set properties of undefined (setting ‘xx‘)的問題及解決方法
TypeError: Cannot set properties of undefined (setting ‘xx‘)
問題描述
我在編寫axios請求后端數(shù)據(jù)的時候,一直出現(xiàn)下面的錯誤前端頁面顯示不出來。
報錯:
TypeError: Cannot set properties of undefined (setting ‘xx’)
原因分析:
this指向的對象發(fā)生了變化(現(xiàn)在this代表axios對象),需要在函數(shù)前將this指向的對象提前保存一下
解決方案:
方法一:回調(diào)函數(shù)使用箭頭函數(shù)來使用。(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="創(chuàng)建時間" 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 方法中 發(fā)請求,因為該方法 可以操作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) * 這樣寫是匿名函數(shù),無法取到tableData的值,所以tableData的值為undefined,不能給undefined的變量賦值 * 解決辦法:1.改為箭頭函數(shù) 2.將this重新賦值給新的變量 */ // .then(function (response) { //成功回調(diào)方法(訪問后臺成功,后臺有數(shù)據(jù)返回,則進入該方法) .then(response=> { //成功回調(diào)方法(訪問后臺成功,后臺有數(shù)據(jù)返回,則進入該方法) console.log(response); console.log(response.data) this.tableData = response.data; }) .catch(function (error) {//失敗回調(diào)方法(訪問后臺失敗,返回失敗的信息,則進入該方法) console.log(error); }); }, methods:{ } } </script>
方法二:暫存this。var th = this; 在內(nèi)部用th.xx代替this.xx
//解決辦法二 var th = this; axios.get('http://localhost:9090/student') // url 請求后臺的地址 .then(function (response) { //成功回調(diào)方法(訪問后臺成功,后臺有數(shù)據(jù)返回,則進入該方法) console.log(response); console.log(response.data) th.tableData = response.data; }) .catch(function (error) {//失敗回調(diào)方法(訪問后臺失敗,返回失敗的信息,則進入該方法) console.log(error); });
到此這篇關(guān)于TypeError: Cannot set properties of undefined (setting ‘xx‘)的文章就介紹到這了,更多相關(guān)Cannot set properties of undefined內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript常用代碼書寫規(guī)范的超全面總結(jié)
這篇文章給大家全面總結(jié)了JavaScript常用代碼的書寫規(guī)范,分別利用推薦和不推薦的兩種示例代碼讓大家更能直接的了解書寫規(guī)范,其實關(guān)于javascript代碼規(guī)范我們應(yīng)該遵循古老的原則:“能做并不意味著應(yīng)該做”,好了,下面我們就來一起看看吧。2016-09-09layui(1.0.9)文件上傳upload,前后端的實例代碼
今天小編就為大家分享一篇layui(1.0.9)文件上傳upload,前后端的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09兼容FireFox 用javascript寫的一個畫圖函數(shù)
兼容FireFox 用javascript寫的一個畫圖函數(shù)...2007-08-08TypeScript?Pinia實戰(zhàn)分享(Vuex和Pinia對比梳理總結(jié))
這篇文章主要介紹了TypeScript?Pinia實戰(zhàn)分享(Vuex和Pinia對比梳理總結(jié)),今天我們再來實戰(zhàn)下官方推薦的新的vue狀態(tài)管理工具Pini,感興趣的小伙伴可以參考一下2022-06-06