You can try this and see if it works, go to your Settings on iPhone, tap on your Apple ID at the top of the screen, scroll down and select "iTunes & App Store" to turn off the music toggle switch, see if the synced music has been removed from your device.
If you want to do that on Mac, go to Music App, press Command + "," to open preferences. In "general", uncheck the first box "Sync Library" and click OK.
If that still doesn't work, you can try to log out from your Apple ID on your device directly.
By the way, to prevent this from happening, you should consider making a backup of your iPhone on your Mac if possible. In this case you can restore the backup to your iPhone directly so that all the files and contents on your iPhone will be completely restored to the condition when you made the backup.
(You'd better keep at least one device logged into your Apple ID, just for more convenient if you want to log your other devices back into your Apple ID again)