This is how it works and isn't a bug. It's two-factor authentication, not prevention.
Yes, it's being sent to that device but, as you mentioned, it's also being sent to all other devices signed-in with the same Apple ID. This is meant to notify the user that a sign-in is being attempted.
To use your example, if you're trying to log into a Mac that means you're not currently logged-in. In that case, the Mac will not get the code because it's only sent to devices that are logged-in with that ID. Your Mac is not logged-in at that point.
You can prevent this in two ways:
- mark the browser/device as always trusted (which makes you less secure - the log in request won’t then broadcast to all your other devices)
- remove that device from your trusted list - all sign in requests will require a different device to receive your 6 digit pin (further locking down that one device - at the expense of not being able to use it as an approved for your iCloud)
If you're already logged-in to your Mac and now you want to add a new device to iCloud, your Mac will get the code because it's a device logged-in with your Apple ID and you've previously 'trusted' that Mac. So now, the code is alerting all your devices that a login attempt is currently being made.
This Apple 2FA page can provide additional info.