其实使用await也要小心,当你的view被干掉了,但是你的delay还没有被清掉,时间到了会继续执行后面的代码,这个this已经无效了
const weakMap = new WeakMap(); // 全局弱引用映射
if (CC_DEV) {
window["my_weakMap "] = weakMap
}
const thenFunc = Promise.prototype.then
Promise.prototype.then = function (onFulfilled, onRejected) {
const that = this
return thenFunc.call(this,
function (value) {
if (typeof onFulfilled === 'function') {
const targetRef = weakMap .get(that);
if (targetRef && !cc.isValid(targetRef)) {
console.warn('Promise liftTarget Component is invalid, skip then callback')
// onRejected?.("liftTarget this is valid")
return;
}
return onFulfilled(value)
}
return value;
},
onRejected)
}
Promise.prototype.isValid= function (target: cc.Node | cc.Component) {
if (!target) return this;
weakMap .set(this, target); // 键是 Promise 实例,值是被弱引用的 target
return this;
}
declare global {
/**全局hook */
interface Promise<T> {
/**处理异步后生命周期问题 */
isValid: (target: cc.Component | cc.Node) => Promise<any>
}
}
//使用示例
await this.delay(100).isVaild(this) //当this 无效后 不会执行后面代码了
后来为了弄这个,我新增了isVaild方法,AI说尽量不这样扩展,但是这是改动已有代码的无二选择了,不然得在所有的await地方去判断 this是不是null,是不是还有效
该代码已经上线运行了,目前没什么问题