You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS出现Uncaught (in promise) TypeError读取null的error属性报错如何解决

Vue 报错 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'error') 修复方案

报错核心:代码在未捕获异常的Promise异步流程中,尝试读取一个null类型值的error属性触发类型错误,可按照对应场景修复:

  • 异步请求返回值处理场景
    触发原因:接口请求异常/请求失败时,返回的响应体被赋值为null,后续未做非空判断直接读取error属性。
    错误代码示例:
    async function getList() {
      const res = await request.get('/xxx/list')
      if (res.error) { // res为null时直接触发报错
        // 错误提示逻辑
      }
    }
    
    修复方案:访问属性前增加非空校验,推荐使用ES6可选链操作符简化写法:
    // 可选链写法,res为null/undefined时会直接返回undefined,不会抛出错误
    if (res?.error) {
      // 错误提示逻辑
    }
    // 原生写法兼容低版本场景
    if (res && res.error) {
      // 错误提示逻辑
    }
    
  • Promise未捕获异常场景
    触发原因:报错前缀Uncaught (in promise)说明异步流程的异常没有被捕获,即使修复了属性读取问题,其他异步异常仍然可能抛出同类未捕获错误。
    修复方案:给所有异步逻辑增加异常捕获逻辑:
    // async/await 写法用try/catch包裹
    async function getList() {
      try {
        const res = await request.get('/xxx/list')
        if (res?.error) {
          // 错误提示逻辑
        }
      } catch (err) {
        // 全局捕获异步流程异常
        console.error('请求异常:', err)
      }
    }
    
    // 原生Promise写法增加catch回调
    request.get('/xxx/list')
      .then(res => {
        if (res?.error) {
          // 错误提示逻辑
        }
      })
      .catch(err => {
        console.error('请求异常:', err)
      })
    
  • 模板渲染场景
    触发原因:响应式变量初始值被设为null,异步请求返回值赋值前,模板直接读取该变量的error属性。
    错误代码示例:
    <script setup>
    import { ref } from 'vue'
    // 初始值设为null
    const userInfo = ref(null)
    </script>
    
    <template>
      <!-- 初始渲染时userInfo为null,触发报错 -->
      <div class="error-tip">{{ userInfo.error }}</div>
    </template>
    
    修复方案:
    <!-- 方案1:模板使用可选链 -->
    <template>
      <div class="error-tip">{{ userInfo?.error }}</div>
    </template>
    
    <!-- 方案2:给响应式变量设置合理初始值 -->
    <script setup>
    import { ref } from 'vue'
    // 初始值设为空对象,避免读取属性时报错
    const userInfo = ref({})
    </script>
    

内容的提问来源于stack exchange,提问作者Newbie_Codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:39:02