網站首頁 編程語言 正文
解決Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id‘)報錯
作者:前端百草閣 更新時間: 2023-07-04 編程語言項目場景:
做黑馬的人資項目時,要讀取store中的userInfo里的id值,報Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id’)錯,起初以為是axios發異步請求的問題,直到后來一直嘗試,終于找到了問題所在!
問題描述
連續訪問對象里的值
例如:我現在user模塊下的state是這樣的,userInfo里的值要等到發請求才會填充
state: {
token: getToken() || '',
userInfo: {
}
請求回來的值是這樣的
那我現在要是還沒請求,userInfo 就還是個空對象,訪問store.user.state.userInfo.data,就是為undefined
但是!!最重要的點來了,如果你接著訪問store.user.state.userInfo.data.id,這時候就不是簡單的undefined
而是 控制臺報錯,Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘id’)
原因分析:
從上面的講解來看,不難知道,你要是訪問對象里不存在的屬性,結果是undefined,但如果你接著還往下訪問,那就會報錯
解決方案:
有兩個辦法解決
1.在userInfo下加一個data
state: {
token: getToken() || '',
userInfo: {
data: {}
}
}
像這樣,你訪問userInfo.data就是一個空對象,再訪問userInfo.data.id的話,就是undefined啦! 就不會報錯了
2.利用?.的訪問方式
store.state.user.userInfo?.data?.id, 利用?.的方式訪問對象中的屬性,要是有一個屬性找不到的話,就會立即返回undefined,
也不會出現報錯的情況
store.state.user?.data?.id
原文鏈接:https://blog.csdn.net/m0_57524265/article/details/131441971
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-08-05 SpringBoot 2.X 整合Redis
- 2022-07-14 python?udp如何實現同時收發信息_python
- 2023-07-07 sklearn.model_selection模塊介紹
- 2021-11-27 nginx中的兩個模塊的proxy_pass的區別解析_nginx
- 2022-08-03 C++單例設計模式詳細講解_C 語言
- 2022-08-16 在WPF中使用Interaction.Triggers_C#教程
- 2022-07-19 react props的特點
- 2023-07-15 react實現路由懶加載
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支