Iterate over callbacks in a more robust way.

This is a remake of commit fb98a678, which I missed when porting the fixes from the "future" branch.