我有以下内容…
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
有人知道是什么引起的吗?
根据MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#issue_with_json.stringify_when_serializing_circular_references
它是一个循环json,不能直接转换。
解决方案1:
https://www.npmjs.com/package/flatted
// ESM
import {parse, stringify, toJSON, fromJSON} from 'flatted';
// CJS
const {parse, stringify, toJSON, fromJSON} = require('flatted');
const a = [{}];
a[0].a = a;
a.push(a);
stringify(a); // [["1","0"],{"a":"0"}]
解决方案2:(同样通过MDN)
https://github.com/douglascrockford/JSON-js
你可能做过类似的事情
<Button onClick={fetchSuggestions}>
未能意识到您已将“事件对象”传递给该函数
如果你不想传递任何东西,只需发送一个空字符串
<Button onClick={() => fetchSuggestions()}>
const fetchSuggestions = async (propsSession) => {
const {
error,
hasNextDoc,
suggestions: moreSuggestions,
} = await fetcher(`/admin/fetchSuggestion`, {
initialRequest: !!propsSession,
session: propsSession || session,
});
}
我通常使用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