前端控制台报错#Uncaught (in promise) TypeError: Cannot read properties of undefined (),用nextTick解决。 vue3

在页面渲染是,控制台报错Uncaught (in promise) TypeError: Cannot read properties of undefined (xxxx),但是页面依然成功渲染了。
原因是接口请求是异步的,而页面上最初进行渲染的时候,还没有拿到接口的值,所以报错了但是正常渲染了,解决方法是通过nexttick加if判断。
也就是将接口请求的办法写在nextTick中,下面是模拟代码:

const list = ref([])
nextTick(() => {
    
    
    test().then((res) => {
    
    
      const testlist= res;
      if (typeof testlist!= "undefined") {
    
    
        list.value = testlist.list;
      }
      console.log(1)
    });
});

在页面上可以看到打印了两次1,因为第一次是没有获取到值的,通过这个操作可以让控制台不报错。

猜你喜欢

转载自blog.csdn.net/weixin_45807026/article/details/125739372