diff --git a/src/base_object-inl.h b/src/base_object-inl.h index 0b620ab864f67b..43bcdc6404fe79 100644 --- a/src/base_object-inl.h +++ b/src/base_object-inl.h @@ -207,7 +207,7 @@ void BaseObject::decrease_refcount() { unsigned int new_refcount = --metadata->strong_ptr_count; if (new_refcount == 0) { if (metadata->is_detached) { - delete this; + OnGCCollect(); } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) { MakeWeak(); } diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc index 447c0842b90d99..d8582918bb616a 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -84,7 +84,16 @@ void HandleWrap::Close(Local close_callback) { void HandleWrap::OnGCCollect() { - Close(); + // When all references to a HandleWrap are lost and the object is supposed to + // be destroyed, we first call Close() to clean up the underlying libuv + // handle. The OnClose callback then acquires and destroys another reference + // to that object, and when that reference is lost, we perform the default + // action (i.e. destroying `this`). + if (state_ != kClosed) { + Close(); + } else { + BaseObject::OnGCCollect(); + } }