[M115] Avoid touching channel after OnSctpDataChannelClosed

(cherry picked from commit eec1810760ccbdf95c68ed0d2c2ae10a8575551a)

Bug: chromium:1454086
Change-Id: I39573b706c4031d091c45a182b13cb3b2dba6233
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/309920
Reviewed-by: Harald Alvestrand <hta@webrtc.org>
Commit-Queue: Tomas Gunnarsson <tommi@webrtc.org>
Cr-Original-Commit-Position: refs/heads/main@{#40332}
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/310921
Reviewed-by: Mirko Bonadei <mbonadei@webrtc.org>
Cr-Commit-Position: refs/branch-heads/5790@{#6}
Cr-Branched-From: 2eacbbc03a4a41ea658661225eb1c8fc07884c33-refs/heads/main@{#40122}
diff --git a/pc/data_channel_controller.cc b/pc/data_channel_controller.cc
index 7fea6c5..93599fd 100644
--- a/pc/data_channel_controller.cc
+++ b/pc/data_channel_controller.cc
@@ -70,6 +70,11 @@
     SctpDataChannel* channel,
     DataChannelInterface::DataState state) {
   RTC_DCHECK_RUN_ON(network_thread());
+
+  // Stash away the internal id here in case `OnSctpDataChannelClosed` ends up
+  // releasing the last reference to the channel.
+  const int channel_id = channel->internal_id();
+
   if (state == DataChannelInterface::DataState::kClosed)
     OnSctpDataChannelClosed(channel);
 
@@ -77,8 +82,7 @@
                                        ? DataChannelUsage::kHaveBeenUsed
                                        : DataChannelUsage::kInUse;
   signaling_thread()->PostTask(SafeTask(
-      signaling_safety_.flag(), [this, channel_id = channel->internal_id(),
-                                 state = state, channel_usage] {
+      signaling_safety_.flag(), [this, channel_id, state, channel_usage] {
         RTC_DCHECK_RUN_ON(signaling_thread());
         channel_usage_ = channel_usage;
         pc_->OnSctpDataChannelStateChanged(channel_id, state);