TypeError: Converting circular structure to JSON

13,161 阅读1分钟

1、报错

image.png 错误翻译:TypeError:转换循环结构为JSON

2、导致错误的代码

    //导致错误的代码:
    
    beforeRouteEnter(to, from, next) {
      next(vm => {
        if (from.path == '/movie/chooseCinema' || from.path == '/movie/chooseCinema_wd') {
          sessionStorage.setItem('chooseCinemaQuery', JSON.stringify(from);
        }
      })
    }

3、解析

一般报错TypeError: Converting circular structure to JSON是因为存在循环引用,并且使用JSON.stringify方法去转化成字符串。下面举一个简单地例子:

//报错代码

const x = { a: 8 };
const b = { x };
b.y = b; // 循环引用
JSON.stringify(b); // 触发报错
//解决

const x = { a: 8 };
const b = { x };
b.y = JSON.parse(JSON.stringify(b)); // 隐式深拷贝,主要实现深拷贝,解除循环引用
JSON.stringify(b);

使用JSON.parse(JSON.stringify(from)) 解决,还是报一样的错!!!

解决办法一

直接删除导致循环引用的代码

解决办法二

beforeRouteEnter(to, from, next) {
      /** 核心代码  */
      var cache = [];
      var str = JSON.stringify(from, function(key, value) {
          if (typeof value === 'object' && value !== null) {
              if (cache.indexOf(value) !== -1) {
                  return;
              }
              cache.push(value);
          }
          return value;
      });
      cache = null; // Enable garbage collection
      /** 核心代码  */
      
      next(vm => {
        if (from.path == '/movie/chooseCinema' || from.path == '/movie/chooseCinema_wd') {
          sessionStorage.setItem('chooseCinemaQuery', str);
        }
      })
    },

问题的关键点是解除循环引用

# TypeError: Converting circular structure to JSON