The issue is because the scope of this has changed inside the $.get handler, so it no longer refers to the current .message element in the iteration. You need to store that reference in a variable for use in the inner scope.
Also note that you can include the required class in the selector and remove the if condition, like this:
setInterval(function() {
$('.message.message-not-read').each(function() {
var $message = $(this);
$.get('message-set-read.php?message-id=' + $message.data('id'), function(data) {
$message.toggleClass('message-not-read', data !== 'is-set-read'));
});
});
}, 5000);
Also note that looping through all your messages and sending an AJAX request for each of them every 5 seconds is a really bad idea. It would make more sense to either invert the logic so that you make a single AJAX request which gets the state of all visible messages on the screen which you can then update, or better yet, use websockets if you need to keep the UI/server data in close synchronisation.