diff --git a/src/libcamera/base/thread.cpp b/src/libcamera/base/thread.cpp
index d62a99f7da..8cc1cea2a7 100644
--- a/src/libcamera/base/thread.cpp
+++ b/src/libcamera/base/thread.cpp
@@ -635,20 +635,19 @@ void Thread::dispatchMessages(Message::Type type, Object *receiver)
 
 	std::list<std::unique_ptr<Message>> &messages = data_->messages_.list_;
 
-	for (std::unique_ptr<Message> &msg : messages) {
-		if (!msg)
-			continue;
-
-		if (type != Message::Type::None && msg->type() != type)
-			continue;
+	for (auto it = messages.begin(); it != messages.end();) {
+		std::unique_ptr<Message> &msg = *it;
 
-		if (receiver && receiver != msg->receiver_)
+		if (!msg ||
+		    (type != Message::Type::None && msg->type() != type) ||
+		    (receiver && receiver != msg->receiver_)) {
+			++it;
 			continue;
+		}
 
 		/*
 		 * Move the message, setting the entry in the list to null. It
-		 * will cause recursive calls to ignore the entry, and the erase
-		 * loop at the end of the function to delete it from the list.
+		 * will cause recursive calls to ignore the entry.
 		 */
 		std::unique_ptr<Message> message = std::move(msg);
 
@@ -660,21 +659,11 @@ void Thread::dispatchMessages(Message::Type type, Object *receiver)
 		messageReceiver->message(message.get());
 		message.reset();
 		locker.lock();
-	}
 
-	/*
-	 * If the recursion level is 0, erase all null messages in the list. We
-	 * can't do so during recursion, as it would invalidate the iterator of
-	 * the outer calls.
-	 */
-	if (!--data_->messages_.recursion_) {
-		for (auto iter = messages.begin(); iter != messages.end();) {
-			if (!*iter)
-				iter = messages.erase(iter);
-			else
-				++iter;
-		}
+		it = messages.erase(it);
 	}
+
+	--data_->messages_.recursion_;
 }
 
 /**
