IndexedDB事务类方法报错:transaction.objectStore is not a function
问题:IndexedDB事务调用objectStore时报错TypeError
我在编写IndexedDB事务相关类方法时,调用transaction.objectStore()时触发错误:Uncaught TypeError: transaction.objectStore is not a function,报错位置在IndexedDB.saveToDataBase方法。已经通过console.log确认storeName的值是reminderList,是正确的。
报错代码实现
saveToDataBase(object, id) { //storeName - name of the storage in the database, //object - the object being saved, //id - id of the object being saved console.log(object, id) console.log(storeName) console.log(database) // new transaction const transaction = this._makeTransaction(storeName, 'readwrite'); const store = transaction.objectStore(storeName); // 报错位置! store.put(object, id); // write record console.log(transaction) }; _makeTransaction(storeName, mode) { return new Promise((resolve, reject) => { let transaction = database.transaction(storeName, mode) transaction.oncomplete = () => { resolve(transaction); // success console.log(transaction) }; transaction.onerror = () => { reject(transaction.error); // failure }; }) };
可行代码实现
saveToDataBase(object, id) { //storeName - name of the storage in the database, //object - the object being saved, //id - id of the object being saved console.log(object, id) console.log(storeName) console.log(database) return new Promise((resolve, reject) => { // new transaction const transaction = this._makeTransaction(storeName, 'readwrite'); const store = transaction.objectStore(storeName); // write record store.put(object, id); // transaction.oncomplete = () => { resolve(true); // success }; transaction.onerror = () => { reject(transaction.error); // failure }; }) }; _makeTransaction(storeName, mode) { let transaction = database.transaction(storeName, mode) return transaction }
报错原因解析
- 错误写法中,
_makeTransaction返回的是Promise对象,而非IndexedDB原生的IDBTransaction实例。你直接把这个Promise赋值给transaction变量后调用objectStore(),相当于在Promise上调用不存在的方法,必然报错。 - 正确写法里,
_makeTransaction直接返回原生事务实例,transaction是真正的IDBTransaction对象,调用objectStore()完全有效。 - 额外问题:错误写法里的
_makeTransaction要等到事务oncomplete才resolve,此时事务生命周期已经结束,就算拿到事务对象也无法再操作objectStore了,这也是逻辑上的错误。
内容的提问来源于stack exchange,提问作者808A
相关产品推荐
相关产品推荐

