关于VUE报错“TypeError: Converting circular structure to JSON"


问题:

[Vue warn]: Error in nextTick: "TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Vue'
    |     property '$options' -> object with constructor 'Object'
    |     property 'router' -> object with constructor 'VueRouter'
    --- property 'app' closes the circle"

翻译过来则是 存在循环引用。

代码报错位置不能显式看到循环引用,因为循环引用的代码不是自己写的,而是框架代码自己实现的,因此发现问题的产生地方更难一点。以下是在 路由中传递使用to from时导致循环引用得问题。
在这里插入图片描述
解决方案

  1. 原理就是把数组或对象转化成JSON,然后再转回来,对于属性值转换
JSON.parse(JSON.stringify(body.config.baseURL))
  1. 对于对象整体转换,通过自定义stringify方法,设置一个全局缓存变量,stringify的第二个参数如果是function时,他会传入每个成员的键和值。使用返回值而不是原始值。如果此函数返回 undefined,则排除成员。根对象的键是一个空字符串:“”
//循环引用转换
                var str = [];
                var cache = JSON.stringify(eventData, function (key, value) {
                    if (typeof value === 'object' && value !== null) {
                        if (str.indexOf(value) !== -1) {
                            return;
                        }
                        str.push(value);
                    }
                    return value;
                });
                str = null;

在使用时则不在报错
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐