Fix use-after-free due to destruction order (#2739)