每当我使用 near-cli
调用合约 view
方法时,它都工作正常,终端以 JSON 格式正确输出结果。
但是当我在我的 Angular 项目中使用 near-api-js
方法调用相同的方法时,它会给出错误:
Error: Uncaught (in promise): TypeError: JSON.stringify cannot serialize cyclic structures.
来自 near-cli
的输出供引用,也是我通过 near-api-js
调用相同方法时的预期输出:
{
files: [
{
owner: 'some string',
key: 'some string',
cid: 'some string'
}
],
length: 1
}
这可能是什么原因造成的,解决办法是什么?
最佳答案
循环引用示例:
var circularReference = {otherData: 123};
circularReference.myself = circularReference;
JSON.stringify(circularReference);
说明:circularReference
通过 circularReference.myself
引用自身。
Mozilla's website有一个很好的示例说明如何找到和删除循环引用:
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123}
您可以修改它,而不是删除循环引用。
不过,这只是对症治疗。最好的方法是首先找出循环引用出现的原因,如果这是由错误引起的,则修复它。
关于javascript - close-api-js,查看合约方法调用给出 : TypeError: JSON. stringify 无法序列化循环结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68476117/