无法读取未定义的 IndexedDB 的 属性 'transaction'

Cannot read property 'transaction' of undefined IndexedDB

我正在使用 IndexDB 创建用户的对象存储,但是在尝试添加用户时,我在 var request = db.transaction(['person'], 'readwrite') 行中收到错误消息。

给出的错误是:

"Uncaught TypeError: Cannot read property 'transaction' of undefined at add (test.js:32) at test.js:45"

我的脚本如下所示:

var request = window.indexedDB.open("connectDB", 1);

request.onerror = function (event) 
{
console.log('The database is opened failed');
};

var db;

request.onsuccess = function (event) 
{
    db = request.result;
console.log('The database is opened successfully');
};

var db;

request.onupgradeneeded = function (event) 
{
    db = event.target.result;
    var objectStore;
    if (!db.objectStoreNames.contains('users'))
    {
        objectStore = db.createObjectStore('users', { keyPath: 'id' });
        objectStore.createIndex('name', 'name', { unique: false });
        objectStore.createIndex('email', 'email', { unique: true });
    }
}

function add() 
{
  var request = db.transaction(['person'], 'readwrite')
    .objectStore('person')
    .add({ id: 1, name: 'Jam', age: 24, email: 'jam@example.com' });

  request.onsuccess = function (event) {
    console.log('The data has been written successfully');
  };

  request.onerror = function (event) {
    console.log('The data has been written failed');
  }
}

add();

如有任何帮助,我们将不胜感激

您似乎在调用未初始化的 add() 期间尝试访问 db(请注意,对 add() 的调用会在您的脚本执行时立即发生).

然而,db 变量仅在成功创建数据库连接时才初始化:

request.onsuccess = function (event) 
{
    db = request.result;
    console.log('The database is opened successfully');

    // It is now safe to interact with the database
};

有多种方法可以解决这个问题,但最简单的方法是将对 add() 的调用移动到 onsuccess 处理程序中,如下所示:

request.onsuccess = function (event) 
{
    db = request.result;
    console.log('The database is opened successfully');

    add(); // Add this
};

// add(); <-- remove this from the end of your script

最后,我注意到您声明了两个 var db; 变量 - 考虑删除其中一个。希望这对您有所帮助!