gpt4 book ai didi

reactjs - react 测试 - UnhandledPromiseRejection

转载 作者:行者123 更新时间:2023-12-05 02:40:57 25 4
gpt4 key购买 nike

我想用 Jest 和 Enzyme 测试我的应用程序。我收到错误:

node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "[object Object]".] {
code: 'ERR_UNHANDLED_REJECTION'
}

这是由于:

async function checkGet() {
const fetchedDB = await db.persons.toArray();
if (fetchedDB.length > 0) {
setPeople(fetchedDB);
return;
} else {
getPeople();
}
}

我试着改变它:

 async function checkGet() {
const fetchedDB = await db.persons.toArray();
fetchedDB.catch((e) => {
console.log(e);
});
if (fetchedDB.length > 0) {
setPeople(fetchedDB);
return;
} else {
getPeople();
}
}

像那样:

  async function checkGet() {
const fetchedDB = await db.persons.toArray().catch((e) => {
console.log(e);
});
if (fetchedDB.length > 0) {
setPeople(fetchedDB);
return;
} else {
getPeople();
}
}

但即使添加了这个,错误仍然存​​在。我正在使用 React 17。这是某种错误吗?

最佳答案

尝试使用 try/catch 包装您的代码。

async function checkGet() {
try {
const fetchedDB = await db.persons.toArray();
if (fetchedDB.length > 0) {
setPeople(fetchedDB);
return;
} else {
getPeople();
}
} catch (err) {
console.log(err);
}
}

try{} 中抛出的所有错误都将在 catch(err){} 中捕获。

关于reactjs - react 测试 - UnhandledPromiseRejection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68368577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com