Dexie报“请求的数据库对象未找到”错误的排查与解决
问题分析与解决方案
核心问题排查
1. 数据来源缺失
demo对象未初始化qunits数组,且setupQunits方法从未被调用,导致插入数据库时没有可写入的数据。
2. 数据库字段不匹配
数据库表定义的字段是step和function,但插入数据时使用的是level和functionName,两者完全不对应,导致查询step字段时无匹配结果。
3. 异步查询处理错误
await that.db.qunits.where('step').belowOrEqual(2)返回的是Dexie的Collection对象,而非实际数据,必须调用.toArray()才能获取数组结果。- 事务结束后再操作
Collection会触发Firefox的NotFoundError,因为事务上下文已失效。
4. 全局变量污染
that = this未声明变量,会将that暴露为全局变量,引发潜在冲突。
修复后的代码
document.addEventListener('DOMContentLoaded', function() { const demo = { qunits: [], // 初始化数组 init: function () { const that = this; // 声明局部变量that,避免全局污染 that.setupQunits(); // 调用初始化数据方法 that.putQunitsIntoDatabase(); }, getBlockQunitAndCreateRandomBlock: async function() { const that = this; try { // 直接在异步函数中查询,无需额外事务包裹(单查询可省略显式事务) that.allValidQunits = await that.db.qunits.where('step').belowOrEqual(2).toArray(); console.log('that.allValidQunits as array:'); console.log(that.allValidQunits); } catch (e) { console.error('查询失败:', e); } }, setupQunits: function() { const that = this; that.qunits.push({ 'step' : 1, 'function' : 'purchase' }); that.qunits.push({ 'step' : 2, 'function' : 'inventory' }); that.qunits.push({ 'step' : 3, 'function' : 'log' }); }, putQunitsIntoDatabase: async function() { const that = this; const dbName = 'myProject'; that.db = new Dexie(dbName); that.db.version(1).stores({ qunits: 'id++,step,function' }); try { await that.db.open(); // 使用原生数组forEach替代jQuery each await that.db.transaction('rw', that.db.qunits, async () => { for (const item of that.qunits) { await that.db.qunits.add({ step: item.step, // 与表定义字段一致 function: item.function }); } }); await that.getBlockQunitAndCreateRandomBlock(); } catch (e) { console.error('操作失败:', e); } } }; demo.init(); });
代码优化建议
- 移除不必要的jQuery依赖:原生JS的数组方法(如
forEach、for...of)完全可以替代jQuery的遍历逻辑,减少外部依赖。 - 统一使用async/await:替代Promise链式调用,让异步代码更易读、更易维护。
- 变量声明规范:所有变量使用
let/const声明,避免全局变量污染。 - 简化事务使用:单操作或简单查询可省略显式事务,Dexie会自动处理;复杂多表操作再使用显式事务。
- 错误处理完善:给所有异步操作添加
try/catch,便于定位问题。 - 避免滥用
that:可以使用箭头函数保留上下文,或者在需要时局部声明that,减少冗余。
内容的提问来源于stack exchange,提问作者Mayor of the Plattenbaus
相关产品推荐
相关产品推荐

