相关文章推荐
曾深爱过的蛋挞  ·  libpthread.so.0: ...·  1 年前    · 
豁达的紫菜  ·  cocoa - How do you ...·  1 年前    · 
beforeRouteEnter ( to, from , next ) { next ( vm => { if ( from . path == '/movie/chooseCinema' || from . path == '/movie/chooseCinema_wd' ) { sessionStorage. setItem ( 'chooseCinemaQuery' , JSON . stringify ( from );

一般报错 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

分类:
前端