Node.js/SQLite3中Run回调this指向错误,如何获取RunResult实例?
解决TypeScript中sqlite3回调this指向错误的问题
问题根源在于你使用了箭头函数作为db.run的回调:箭头函数没有独立的this上下文,会自动捕获外层作用域(即Log实例的save方法)的this,导致回调里的this指向Log而非预期的RunResult。
修复方案
改用普通函数作为回调,同时在外层保存当前Log实例的引用,这样既能获取RunResult的lastID,又能更新Log实例的id:
class Log { public id: number; public text: string; constructor(text: string){ // 注意原代码中construct拼写错误,应为constructor this.text = text; } save(){ const logInstance = this; // 保存当前Log实例的引用 db.run( `insert into logs(text) values (?) `, this.text, function(this: RunResult, err: Error | null) { // 使用普通函数作为回调 if(err){ // 处理错误逻辑 return; } console.log(this); // 此时this为RunResult实例 logInstance.id = this.lastID; // 更新Log实例的id } ) } }
补充说明
- 普通函数作为
db.run的回调时,sqlite3会自动将this绑定为RunResult实例,符合类型声明的预期。 - 原代码中的
construct是拼写错误,需修正为constructor才能正常实例化Log类。
内容的提问来源于stack exchange,提问作者Xiaodong Liu
相关产品推荐
相关产品推荐

