我有以下内容…

chrome.extension.sendRequest({
  req: "getDocument",
  docu: pagedoc,
  name: 'name'
}, function(response){
  var efjs = response.reply;
});

调用下面的..

case "getBrowserForDocumentAttribute":
  alert("ZOMG HERE");
  sendResponse({
    reply: getBrowserForDocumentAttribute(request.docu,request.name)
  });
  break;

然而,我的代码从未达到“ZOMG HERE”,而是在运行chrome.extension.sendRequest时抛出以下错误

 Uncaught TypeError: Converting circular structure to JSON
 chromeHidden.JSON.stringify
 chrome.Port.postMessage
 chrome.initExtension.chrome.extension.sendRequest
 suggestQuery

有人知道是什么引起的吗?


当前回答

在尝试用jQuery构建下面的消息时,我也遇到过同样的错误。循环引用发生在reviewerName被错误地分配给msg.detail.reviewerName时。JQuery的.val()修复了这个问题,参见最后一行。

var reviewerName = $('reviewerName'); // <input type="text" id="taskName" />;
var msg = {"type":"A", "detail":{"managerReview":true} };
msg.detail.reviewerName = reviewerName; // Error
msg.detail.reviewerName = reviewerName.val(); // Fixed

其他回答

在我的情况下,我只是忘记使用async/await的东西,而构建路由:

app.get('/products', async (req, res) => {
    const products = await Product.find();
    res.send(products );
});

我通常使用circular-json npm包来解决这个问题。

// Felix Kling's example
var a = {};
a.b = a;
// load circular-json module
var CircularJSON = require('circular-json');
console.log(CircularJSON.stringify(a));
//result
{"b":"~"}

注意:CircularJSON已弃用,我现在使用flatted(来自CircularJSON的创建者):

// ESM
import {parse, stringify} from 'flatted/esm';

// CJS
const {parse, stringify} = require('flatted/cjs');

const a = [{}];
a[0].a = a;
a.push(a);

stringify(a); // [["1","0"],{"a":"0"}]

来自:https://www.npmjs.com/package/flatted

这可以工作并告诉您哪些属性是循环的。它还允许使用引用重新构造对象

  JSON.stringifyWithCircularRefs = (function() {
    const refs = new Map();
    const parents = [];
    const path = ["this"];

    function clear() {
      refs.clear();
      parents.length = 0;
      path.length = 1;
    }

    function updateParents(key, value) {
      var idx = parents.length - 1;
      var prev = parents[idx];
      if (prev[key] === value || idx === 0) {
        path.push(key);
        parents.push(value);
      } else {
        while (idx-- >= 0) {
          prev = parents[idx];
          if (prev[key] === value) {
            idx += 2;
            parents.length = idx;
            path.length = idx;
            --idx;
            parents[idx] = value;
            path[idx] = key;
            break;
          }
        }
      }
    }

    function checkCircular(key, value) {
      if (value != null) {
        if (typeof value === "object") {
          if (key) { updateParents(key, value); }

          let other = refs.get(value);
          if (other) {
            return '[Circular Reference]' + other;
          } else {
            refs.set(value, path.join('.'));
          }
        }
      }
      return value;
    }

    return function stringifyWithCircularRefs(obj, space) {
      try {
        parents.push(obj);
        return JSON.stringify(obj, checkCircular, space);
      } finally {
        clear();
      }
    }
  })();

删除大量噪音的例子:

{
    "requestStartTime": "2020-05-22...",
    "ws": {
        "_events": {},
        "readyState": 2,
        "_closeTimer": {
            "_idleTimeout": 30000,
            "_idlePrev": {
                "_idleNext": "[Circular Reference]this.ws._closeTimer",
                "_idlePrev": "[Circular Reference]this.ws._closeTimer",
                "expiry": 33764,
                "id": -9007199254740987,
                "msecs": 30000,
                "priorityQueuePosition": 2
            },
            "_idleNext": "[Circular Reference]this.ws._closeTimer._idlePrev",
            "_idleStart": 3764,
            "_destroyed": false
        },
        "_closeCode": 1006,
        "_extensions": {},
        "_receiver": {
            "_binaryType": "nodebuffer",
            "_extensions": "[Circular Reference]this.ws._extensions",
        },
        "_sender": {
            "_extensions": "[Circular Reference]this.ws._extensions",
            "_socket": {
                "_tlsOptions": {
                    "pipe": false,
                    "secureContext": {
                        "context": {},
                        "singleUse": true
                    },
                },
                "ssl": {
                    "_parent": {
                        "reading": true
                    },
                    "_secureContext": "[Circular Reference]this.ws._sender._socket._tlsOptions.secureContext",
                    "reading": true
                }
            },
            "_firstFragment": true,
            "_compress": false,
            "_bufferedBytes": 0,
            "_deflating": false,
            "_queue": []
        },
        "_socket": "[Circular Reference]this.ws._sender._socket"
    }
}

为了重建调用JSON.parse(),然后遍历属性寻找[Circular Reference]标记。然后把它切下来…eval……它将此设置为根对象。

不要评估任何可能被黑的东西。更好的做法是执行string.split('.'),然后按名称查找属性来设置引用。

在我的情况下,当我在服务器端使用async函数使用mongoose获取文档时,我得到了这个错误。原来,原因是我忘记在调用find({})方法之前放置await。添加这个部分解决了我的问题。

你可能做过类似的事情

<Button onClick={fetchSuggestions}>

未能意识到您已将“事件对象”传递给该函数

如果你不想传递任何东西,只需发送一个空字符串

<Button onClick={() => fetchSuggestions()}>
  const fetchSuggestions = async (propsSession) => {
    const {
      error,
      hasNextDoc,
      suggestions: moreSuggestions,
    } = await fetcher(`/admin/fetchSuggestion`, {
      initialRequest: !!propsSession,
      session: propsSession || session,
    });
  }